Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gwokae
Last active November 2, 2016 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwokae/1e2914870f4a1b6cd4814ad915ea9eed to your computer and use it in GitHub Desktop.
Save gwokae/1e2914870f4a1b6cd4814ad915ea9eed to your computer and use it in GitHub Desktop.
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 );
}
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