sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.18k stars 167 forks source link

Bug: `random.shuffle()` function is broken and does not work as expected #353

Open EgizianoEG opened 12 months ago

EgizianoEG commented 12 months ago

The 'shuffle' function has a bug when it fails to return an array that is shuffled. The same incorrect behavior is occurring on the documentation object as well.

Reproducible code:

const { shuffle } = require("radash");

const count = {
  123: 0,
  132: 0,
  213: 0,
  231: 0,
  321: 0,
  312: 0,
};

for (let i = 0; i < 1_000_000; i++) {
  const array = [1, 2, 3];
  shuffle(array);
  count[array.join("")]++;
}

for (const key in count) {
  console.log(`${key}: ${count[key]}`);
}

/** 
 * Logs the following:
   123: 1000000
   132: 0
   213: 0
   231: 0
   312: 0
   321: 0
 */
UnKnoWn-Consortium commented 6 months ago

shuffle does not manipulate the original array. Instead the changes are made to a new one that is returned. Your code will work if you make this change:

for (let i = 0; i < 1_000_000; i++) {
  let array = [1, 2, 3];
  array = shuffle(array);
  count[array.join("")]++;
}