From 075fe8930927b47ef0738be3327f86ac8d27205c Mon Sep 17 00:00:00 2001 From: pyoor Date: Thu, 26 Jul 2018 19:26:27 -0400 Subject: [PATCH] Refactor random.subset to pop items from cloned array --- lib/random/random.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/random/random.js b/lib/random/random.js index 63a1f61..eb4b901 100644 --- a/lib/random/random.js +++ b/lib/random/random.js @@ -180,18 +180,29 @@ class random { return newArray } + /** + * Select an array containing a subset of 'list' + * @param list + * @param limit + * @returns {Array} + */ static subset (list, limit) { if (!(Array.isArray(list))) { logger.traceback() throw new TypeError(`random.subset() received non-array type: (${list})`) } + if (typeof limit !== 'number') { limit = random.number(list.length + 1) } - let result = [] - for (let i = 0; i < limit; i++) { - result.push(random.pick(list)) + + // Deepclone list + const temp = JSON.parse(JSON.stringify(list)) + const result = [] + while (limit--) { + result.push(random.pop(temp)) } + return result }