Created
March 4, 2021 00:54
-
-
Save ztrehagem/bc440653cb04a819d51a5dd16bcf23db to your computer and use it in GitHub Desktop.
This file contains 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
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