Last active
November 2, 2016 09:51
-
-
Save gwokae/1e2914870f4a1b6cd4814ad915ea9eed to your computer and use it in GitHub Desktop.
This file contains 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
Array.prototype.sample = function(count = 1){ | |
let {length} = this; | |
if( count > length ){ | |
count = length; | |
} | |
return this.map( (item, idx) => { | |
return {item, rnd: Math.random()}; | |
}) | |
.sort( (a, b) => a.rnd - b.rnd ) | |
.slice( length - count ) | |
.map( item => item.item ); | |
} |
This file contains 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
Array.prototype.sample = function(count = 1){ | |
let {length} = this; | |
if( count > length ){ | |
count = length; | |
} | |
let result = []; | |
while(result.length < count) { | |
let idx = Math.floor(length * Math.random()); | |
if(result.indexOf(idx) === -1){ | |
result.push(idx); | |
} | |
} | |
return this.filter( (item, idx) => result.indexOf(idx) !== -1 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment