UNPKG

@grandom/shuffle

Version:

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

66 lines (62 loc) 2.39 kB
'use strict'; var core = require('@grandom/core'); var index = require('../utils/index.js'); var index$1 = require('./ExcludeFilter/index.js'); class RandomStringShuffle extends core.RandomGenerator { constructor(engine) { super(engine); this.shuffle = this.shuffle.bind(this); } // ----------------------------------------------------------------------------------------------- canBeParsed(arg1) { return typeof arg1 === 'string'; } parse(arg1, arg2, arg3) { if (arg1.length < 1) { return ''; } const { count, options } = index.getRest(arg1, arg2, arg3); // ------------------------------------------------------------------------- const exclude = 'exclude' in options ? new index$1(options.exclude) : undefined; const filter = typeof options.filter === 'function' ? options.filter : undefined; // ------------------------------------------------------------------------- const characters = [...arg1]; const pool = []; let length = count === -1 ? characters.length : count; // clamp length, disallow larger count, than the input string if (length > characters.length) { length = characters.length; } // preshuffle, to allow all characters to be picked from, if count // is smaller, than the input string length this._engine.shuffleArray(characters); for (let i = 0; i < length; i++) { const character = characters[i]; if (exclude?.matches(character) === true) { continue; } if (filter?.(character) === false) { continue; } pool.push(character); } return pool.join(''); } // ----------------------------------------------------------------------------------------------- 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 a string, got: ${arg1} (typeof === '${typeof arg1}').`); } } module.exports = RandomStringShuffle; //# sourceMappingURL=index.js.map