Created
June 10, 2020 10:57
-
-
Save takumifukasawa/ae9c488d0c6ad09c638782f0a0ad1fa3 to your computer and use it in GitHub Desktop.
ES6: Prepare the cache so that the same elements are not extracted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* # usage | |
* const pool = randomSampleInCache(array, 5); | |
* const elem = pool.pick(); | |
* | |
* TODO: clamp cacheNum in [0 ... list.length] | |
*/ | |
import { difference, sample, range } from "lodash" | |
export default (list, cacheNum = 1) => { | |
if (list.length === 1) cacheNum = 0 | |
const cached = new Array(cacheNum) | |
const indexes = range(list.length) | |
function pick() { | |
const diffIndexes = difference(indexes, cached) | |
const pickIndex = sample(diffIndexes) | |
if (cacheNum > 0) { | |
cached.push(pickIndex) | |
if (cached.length > cacheNum) cached.shift() | |
} | |
return list[pickIndex] | |
} | |
return { | |
list, | |
pick, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment