samedi 1 décembre 2018

returning a function that uses a var declared outside of it

this is a function that chooses items randomly from a given array until all are taken and only then repeating

i actually copied the code from a post because i couldn't understand how the variable copy's scope works .

PS : here's the post How to efficiently randomly select array item without repeats?

thanks in advance for the help .

function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length < 1) { copy = array.slice(0); }
    var index = Math.floor(Math.random() * copy.length);
    var item = copy[index];
    copy.splice(index, 1);
    return item;
  };
}

var chooser = randomNoRepeats(['Foo', 'Bar', 'Gah']);
chooser(); // => "Bar"
chooser(); // => "Foo"
chooser(); // => "Gah"
chooser(); // => "Foo" -- only repeats once all items are exhausted.




Aucun commentaire:

Enregistrer un commentaire