UNPKG

@leetcoderoulette/roulette

Version:

https://leetcoderoulette.com roulette library

70 lines (69 loc) 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); ; const DEFAULT_OPTIONS = { popWhenGettingObject: true, enableSetReset: true }; /** * Roulette class to get a random values from a set of values. */ class Roulette { /** * Creates new Roulette instance with initial set. * @param values Initial values array. * @param options Roulette options. */ constructor(values, options) { this.options = DEFAULT_OPTIONS; if (values.length === 0) { throw Roulette.NO_VALUES_ERROR; } this.set = new Set(values); this.options = Object.assign(Object.assign({}, this.options), options); } /** * Gets a random value from set and deletes it. * @returns A random value from the set. */ pop() { if (this.set.size === 0) { throw Roulette.NO_VALUES_ERROR; } const index = Math.floor(Math.random() * this.set.size); const values = Array.from(this.set); const value = values[index]; if (this.options.popWhenGettingObject) { this.set.delete(value); } return value; } /** * Gets the number of values left in the set. * @returns Size of the set. */ get size() { return this.set.size; } /** * Gets array of available problems from problemset. * @returns Array of problems in the problemset. */ get values() { return Array.from(this.set); } /** * Sets the set to the provided objects. */ set values(values) { if (!this.options.enableSetReset) { throw new Error("Unable to reset set when enableSetReset is false. Try changing this value to true."); } if (values.length === 0) { throw Roulette.NO_VALUES_ERROR; } this.set = new Set(values); } } exports.default = Roulette; Roulette.NO_VALUES_ERROR = new Error("set is empty.");