Skip to content

Commit

Permalink
feat: Array.shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Aug 21, 2020
1 parent 0bad829 commit 8ab3631
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions _es5-ext/array/shuffle.js
Original file line number Diff line number Diff line change
@@ -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;
};

0 comments on commit 8ab3631

Please sign in to comment.