Refactor random.subset to pop items from cloned array

This commit is contained in:
pyoor 2018-07-26 19:26:27 -04:00
parent 40eee0a442
commit 075fe89309

View file

@ -180,18 +180,29 @@ class random {
return newArray return newArray
} }
/**
* Select an array containing a subset of 'list'
* @param list
* @param limit
* @returns {Array}
*/
static subset (list, limit) { static subset (list, limit) {
if (!(Array.isArray(list))) { if (!(Array.isArray(list))) {
logger.traceback() logger.traceback()
throw new TypeError(`random.subset() received non-array type: (${list})`) throw new TypeError(`random.subset() received non-array type: (${list})`)
} }
if (typeof limit !== 'number') { if (typeof limit !== 'number') {
limit = random.number(list.length + 1) limit = random.number(list.length + 1)
} }
let result = []
for (let i = 0; i < limit; i++) { // Deepclone list
result.push(random.pick(list)) const temp = JSON.parse(JSON.stringify(list))
const result = []
while (limit--) {
result.push(random.pop(temp))
} }
return result return result
} }