Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created June 10, 2020 10:57
Show Gist options
  • Save takumifukasawa/ae9c488d0c6ad09c638782f0a0ad1fa3 to your computer and use it in GitHub Desktop.
Save takumifukasawa/ae9c488d0c6ad09c638782f0a0ad1fa3 to your computer and use it in GitHub Desktop.
ES6: Prepare the cache so that the same elements are not extracted
/*
* # 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