UNPKG

@leetcoderoulette/roulette

Version:

https://leetcoderoulette.com roulette library

68 lines (67 loc) 1.88 kB
; const DEFAULT_OPTIONS = { popWhenGettingObject: true, enableSetReset: true }; /** * Roulette class to get a random values from a set of values. */ export default class Roulette { static NO_VALUES_ERROR = new Error("set is empty."); set; options = DEFAULT_OPTIONS; /** * Creates new Roulette instance with initial set. * @param values Initial values array. * @param options Roulette options. */ constructor(values, options) { if (values.length === 0) { throw Roulette.NO_VALUES_ERROR; } this.set = new Set(values); this.options = { ...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); } }