#54 - Pool of random numbers

Date: 2019-03-30 12:00 - JS

Class that draws unique random ids from a pool of numbers

class NumberPool {
	constructor(max) {
		this.pool = {};
		this.max = max;
    }
	draw() {
		let randomId;
        do {
            randomId = '' + ((1 + Math.random() * this.max) | 0);
        } while (this.pool[randomId] != undefined);
        var drawn = { number: randomId };
		drawn.dispose = () => {
			delete this.pool[randomId];
        }
		this.pool[randomId] = true;
		return drawn;
    }
    reset() {
        this.pool = {};
    }
}

Previous snippet | Next snippet