Last active
September 20, 2016 13:50
-
-
Save juliovedovatto/4f86b6800b5134cdf502ee3940798a4f to your computer and use it in GitHub Desktop.
ECMAScript 6 Array shuffle
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
// METHOD 1 | |
Object.assign(Array.prototype, { | |
shuffle() { | |
let m = this.length, i; | |
while (m) { | |
i = (Math.random() * m--) >>> 0; | |
[this[m], this[i]] = [this[i], this[m]]; | |
} | |
return this; | |
} | |
}); |
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
// METHOD 2 | |
Object.assign(Array.prototype, { | |
shuffle() { | |
return this.sort(() => 0.5 - Math.random()); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment