Created
June 17, 2015 20:20
-
-
Save jgdovin/2cc63c2e36486113833f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var shuffle = function (arr) { | |
//check to make sure we were not passed an empty value. | |
if (!arr) { | |
console.error('Target of shuffling cannot be empty.'); | |
return false; | |
} | |
//check to make sure the value we were passed is an Array | |
if (arr.constructor != Array) { | |
console.error('Target of shuffling must be of type Array'); | |
return false; | |
} | |
var result = []; | |
//as long as the array has a length keep running. | |
while (arr.length) { | |
//we will push a random number between 0 and the given array's length - 1 to account for | |
//arrays starting at 0. Splice returns an array so we will pop the element out of | |
//that array by pulling it out of the original array and pushing it to the result array. | |
//This technique is similar to the Fischer-Yates shuffling technique. | |
result.push(arr.splice(_.random(0, arr.length - 1), 1).pop()) | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment