Skip to content

Instantly share code, notes, and snippets.

@ztrehagem
Created March 4, 2021 00:54
Show Gist options
  • Save ztrehagem/bc440653cb04a819d51a5dd16bcf23db to your computer and use it in GitHub Desktop.
Save ztrehagem/bc440653cb04a819d51a5dd16bcf23db to your computer and use it in GitHub Desktop.
class RandomAccessPool<T> {
readonly items: readonly T[]
protected pool: T[] = []
constructor(items: T[]) {
this.items = items
}
get() {
if (!this.pool.length) {
this.pool = [...this.items]
}
const index = Math.floor(Math.random() * this.pool.length)
return this.pool.splice(index, 1)[0]
}
}
const rap = new RandomAccessPool([1,2,3])
for (const it of [...Array(25)]) {
console.log(rap.get())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment