UNPKG

@grandom/shuffle

Version:

A configurable, flexible, seedable, and overall great random shuffler.

52 lines (48 loc) 1.7 kB
'use strict'; var core = require('@grandom/core'); var index = require('../utils/index.js'); class RandomObjectShuffle extends core.RandomGenerator { constructor(engine) { super(engine); this.shuffle = this.shuffle.bind(this); } // ----------------------------------------------------------------------------------------------- canBeParsed(arg1) { return arg1 !== null && typeof arg1 === 'object'; } parse(arg1, arg2, arg3) { const keys = Object.keys(arg1); if (keys.length < 1) { return {}; } const { count, options } = index.getRest(arg1, arg2, arg3); const filter = typeof options.filter === 'function' ? options.filter : undefined; const length = count === -1 ? keys.length : count; const pool = {}; this._engine.shuffleArray(keys); for (let i = 0; i < length; i++) { const key = keys[i]; const value = arg1[key]; if (filter?.(key, value) === false) { continue; } pool[key] = value; } return pool; } // ----------------------------------------------------------------------------------------------- shuffle(arg1, arg2, arg3) { if (this.canBeParsed(arg1)) { return this.parse(arg1, arg2, arg3); } throw new TypeError( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Must be called with an object, got: ${arg1} (typeof === '${typeof arg1}').`); } } module.exports = RandomObjectShuffle; //# sourceMappingURL=index.js.map