Naming
The name pickRandomItemFrom
is too long
pick
implies removal which the function does not do
from
is redundant.
Thus pickRandomItemFrom
can simply be randomItem
with Item
implying an array
Ignoring the obvious problems and removing the unnecessary currying we can rewrite your code as
const randomItem = array => array[Math.floor(Math.random() * array.length]);
console.log(randomItem(items));
The function Math.random
is not pure because you can not control the seed value. Using it in any function will make that function impure.
To be pure a function must return the same value given the same input.
You can create a pure random function but the function must take a seed value from which to calculate a random value.
Example
const seededRandom = (() => {
const max = 2576436549074795, add = 8507698654323524, scale = 8765432352450986;
return seed => ((scale * Math.abs(Math.floor(seed))) + add) % max;
})();
Selecting random item
You can then create the randomItem
function using
const randomItem = ((rand) => (arr, seed) => arr[rand(seed) % arr.length])(seededRandom);
Used as follows
console.log(randomItem([1,2,3], Date.now()));
Note that the function can be called many times every ms. To ensure a unique seed modify the seed each call.
Example
const seededRandom = (() => {
const max = 2576436549074795, add = 8507698654323524, scale = 8765432352450986;
return seed => ((scale * Math.abs(Math.floor(seed))) + add) % max;
})();
const randomItem = (rand => (arr, seed) => arr[rand(seed) % arr.length])(seededRandom);
const test = [1, 2, 3, 4, 5, 6, 7, 8];
var seed = Date.now();
console.log(randomItem(test, seed++));
console.log(randomItem(test, seed++));
console.log(randomItem(test, seed++));
console.log(randomItem(test, seed++));
// or
console.log("-------------------------");
console.log(randomItem(test, seed = seededRandom(seed)));
console.log(randomItem(test, seed = seededRandom(seed)));
// or curried
const randomizeItems = ((random) => (arr, seed) => () => arr[seed = random(seed) % arr.length])(seededRandom);
const randomTestItem = randomizeItems(test, seed);
console.log("-------------------------");
console.log(randomTestItem())
console.log(randomTestItem())
console.log(randomTestItem())
console.log(randomTestItem())
Note Random means pseudo random in context of this answer