I have a 2-liner here which… does the trick, but its just a bit lame looking really:
var n = 'configOb_'+Math.floor(Math.random()*100);
while( document[n] !== undefined ){ n = 'configOb_'+Math.floor(Math.random()*100); }
It’s basically generating a unique id. It’s important to note that I cannot use any JS dependency files, as this script is executed before my YUILoader instance finishes up (the above script is located within <body />, YUILoader waits for DOM readiness).
So what I’m after is any clever optimisations of the above 2-liner.
Thanks!
Edit: Er, sorry, I did select that as code – but it isn’t holding… hopefully this time…
You haven’t stated what you want it optimised for, speed or size but I’ll optimise it for correctness if you wish 🙂
As you approach the 100-object limit, the running time for that loop is going to get longer and longer, right up to the point where you’ve used all the objects, when it will become infinite.
I would just start at 0 and go up until you find a free slot, something like:
Of course, you’re still limited, but it’s well beyond the 100 bound that your random function gives you. In addition, the run time will still increase as the number of objects increases but at least in a more deterministic way.