From 8ab363156329f40f755e4f10382a2e692a89ed3f Mon Sep 17 00:00:00 2001 From: SukkaW Date: Fri, 21 Aug 2020 17:34:56 +0800 Subject: [PATCH] feat: Array.shuffle --- _es5-ext/array/shuffle.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 _es5-ext/array/shuffle.js diff --git a/_es5-ext/array/shuffle.js b/_es5-ext/array/shuffle.js new file mode 100644 index 00000000..37c54b4d --- /dev/null +++ b/_es5-ext/array/shuffle.js @@ -0,0 +1,25 @@ +"use strict"; + +var random = Math.random, isArray = Array.isArray; + +module.exports = function (input) { + if (!isArray(input)) throw new TypeError("input must be an Array!"); + + // Make a clone of original array + var $array = input.slice(0); + + var sourceIndex = input.length; + var destinationIndex = 0; + + // Pre-assign the size of array + var shuffled = new Array(sourceIndex); + + while (sourceIndex) { + // eslint-disable-next-line no-bitwise + var randomIndex = (sourceIndex * random()) | 0; + shuffled[destinationIndex++] = $array[randomIndex]; + $array[randomIndex] = $array[--sourceIndex]; + } + + return shuffled; +};