habitica/website/common/script/libs/randomVal.js

20 lines
485 B
JavaScript
Raw Normal View History

import values from 'lodash/values';
import keys from 'lodash/keys';
2016-03-08 17:58:39 +00:00
2019-10-01 15:53:48 +00:00
export function trueRandom () {
return Math.random();
}
2016-09-26 13:14:18 +00:00
// Get a random property from an object
// returns random property (the value)
2019-10-01 15:53:48 +00:00
export default function randomVal (obj, options = {}) {
2019-10-08 14:57:10 +00:00
const array = options.key ? keys(obj) : values(obj);
const random = options.predictableRandom || trueRandom();
2016-03-08 17:58:39 +00:00
array.sort();
2019-10-08 14:57:10 +00:00
const randomIndex = Math.floor(random * array.length);
return array[randomIndex];
2019-10-08 14:57:10 +00:00
}