Some good javascript tips & handy functions
code.google.com
code.google.com
[ y for ( y in [5,6,7,8,9] ) ] // is [0,1,2,3,4]
and [ y for each ( y in [5,6,7,8,9] ) ] // is [5,6,7,8,9]
Because in for extracts index names, and for each extracts the values.It will probably be a long time before 1.8 is supported by all browsers.
http://www.python.org/dev/peps/pep-0289/
The generator part in the example is the '(y in [])' the rest is a list comprehension (a short way of writing for loops that can be implemented very efficiently in a language and will return a list).
[UPDATE] Found a better explanation that also explains expression closures at http://ejohn.org/blog/javascript-18-progress/
list = list.sort(function() Math.random() > 0.5 ? 1 : -1);
I'm wondering just how reliably random the result is. Does JavaScript make any guarantee whether the comparison function will only be called once for a given pair of values, and if not, could this affect the result?
Granted, no real world sort is that simple, and it's even possible that the "clever technique" will produce an unbiased permutation for some sorting algorithms. But why waste time thinking about this when the Knuth shuffle, a proper way to randomly permute a list, only takes a few lines of code more and is so well-documented?
(Or at least, it came out that way reliably after several runs of a million iterations each time).
Since a value sorted this way has a decreasing chance to be swapped an increasing number of positions, this result makes perfect sense.
I did a bit of playing with this in Firefox, sorting the array [0,1,2,3,4,5,6,7,8,9] and then testing the mean of the first 5 vs the mean of the second 5, over 10,000 iterations. Then, based on the deviation from 4.5 in each set, I nudged the random cutoff up or down.
It seems to result in most evenly distributed randomness if you change the 0.5 to 0.36725 or so. When I tracked the values to return the same result for the same pair every time, it converged almost exactly on 0.375 every time.
These numbers seem suspiciously round to me.