mercredi 24 février 2016

Random select array with remove items (jQuery)

I'm trying to find a way to get values from an array of random way without repeating them, I found the following solution:

var letters = ["A", "B", "C"];
var getRandom = (function(array) {
  var notGivenItems = array.map(function(el) {
    return el;
  });
  var getIndex = function() {
    return Math.floor(Math.random() * notGivenItems.length);
  };

  return function() {
    if (notGivenItems.length === 0) {
      return;
    }

    return notGivenItems.splice(getIndex(), 1)[0];
  };
})(letters);

console.log(getRandom());
console.log(getRandom());
console.log(getRandom());
console.log(getRandom());

If I print the console.log() 4 times, at last, the array appears as undefined, and that's precisely what I need. However, I need (function () {... don't be fired automatically, because the value that comes via AJAX. So, should be something like:

var letters = ["A", "B", "C"];

function selec() {

  var getRandom = (function(array) {
    var notGivenItems = array.map(function(el) {
      return el;
    });
    var getIndex = function() {
      return Math.floor(Math.random() * notGivenItems.length);
    };

    return function() {
      if (notGivenItems.length === 0) {
        return;
      }

      return notGivenItems.splice(getIndex(), 1)[0];
    };
  })(letters);

  return getRandom();
}

console.log(selec());

But then, the function continues printing values continuously, without return undefined. Can one please help me out?




Aucun commentaire:

Enregistrer un commentaire