jeudi 16 août 2018

Get permanent array item based on string

I need to get a random array item based on hash calculated for the string passed:

var animals = [ 'dog', 'cat', 'horse', 'cow', 'tiger', 'trump' ];
function getFixedItem(str, arr) {
  //magic goes here
  var hash = anyFunctionToCalcHash(str);
  var magicNumber = ???; // calculated based on hash, must be between 0 and arr.length - 1
  return arr[magicNumber];
}

Expected something like:

getFixedItem('john doe', animals); // returns cat
getFixedItem('john moe', animals); // returns horse
getFixedItem('john doe', animals); // returns cat
getFixedItem('abc102030', animals); // returns trump
getFixedItem('john doe', animals); // returns cat




Aucun commentaire:

Enregistrer un commentaire