Proposal for additional array methods

I started learning Python not long, so I discovered that some programs I'll have to implement from scratch in JavaScript to work with Arrays, are methods in Python, the likes of random.choice(), random.shuffle() I'll use these to work with lists most of the time in Python. What if we can implement this for arrays.

Moreso, if we can look into other languages and see if some of the methods for working with similar data structures in JavaScript can be implemented in JavaScript too.

2 Likes

Shuffling's way harder than you'd think to do right - the gold standard for it requires enough bits of RNG state to hold all possible mutations in order to hit all permutations and for all but small arrays (of <= 34 entries), they can't even use what they use for Math.random().

  • If they use xorshift1024* (fails a couple major statistical tests), they can shuffle arrays up to 170 entries and still potentially hit every permutation.
  • If they use the WELL44497a (fairly slow and heavy), they can shuffle arrays up to 4199 entries and still potentially hit every permutation.
  • About anything else would require a hardware RNG.

And yes, I'm saying that Python's default is actually very bad.


Random choice I'm not a fan of - it'd be better if we just got a Math.randomInt(min, max) instead that was effectively min + Math.floor(Math.random() * (max - min)), but something engines could optimize for and knock out the bias in. Then, you could do array[Math.randomInt(0, array.length)] and call it a day. (Also, in my experience, random integers are way more useful in contexts outside of array handling.)

7 Likes

Yeah, Math.random(min, max) is cool :+1:

I was thinking about the exact same thing. It comes up almost anywhere in the JS having to define const randomChoice = (x) ⇒ x[Math.floor(Math.random()*x.length)] every single time feels so bad.