UNPKG

@provably-fair/shuffle

Version:

Array shuffling functionality for provably fair games

42 lines (34 loc) 1.83 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.shuffle = undefined; var _core = require('@provably-fair/core'); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /** * Shuffles an array based on the given seeds, using the given HMAC algorithm. * @param {[]} arr Array to be shuffled. * @param {string} hmacAlgorithm Algorithm used for computing the HMAC of the given seed pair. * @param {string|Buffer} secretSeed Secret seed used as HMAC key. * @param {string|Buffer} [publicSeed] Public seed used as HMAC data. To prove fairness of random * outputs, the hash of `secretSeed` shall be known before revealing `publicSeed`. * @param {function} [hmacBufferUIntParser] Function to be used for parsing a UInt from the * generated HMAC buffer. * @param {function} [fallbackProvider] Function to provide a fallback value in a given range * whether no appropriate number can be parsed from the generated HMAC buffer. * @returns {[]} A new array instance containing every element of the input. */ var shuffle = exports.shuffle = function shuffle(arr, hmacAlgorithm, secretSeed, publicSeed, hmacBufferUIntParser, fallbackProvider) { var result = [].concat(_toConsumableArray(arr)); for (var i = arr.length - 1; i > 0; i -= 1) { // Generate a random integer within [0, i] var j = (0, _core.randomInt32)(hmacAlgorithm, secretSeed, publicSeed + '-' + i, 0, i + 1, hmacBufferUIntParser, fallbackProvider); // Exchange `result[i]` and `result[j]` var _ref = [result[j], result[i]]; result[i] = _ref[0]; result[j] = _ref[1]; } return result; }; exports.default = shuffle; //# sourceMappingURL=index.js.map