Skip to content

Instantly share code, notes, and snippets.

@bollwyvl
Created December 5, 2012 00:48
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 bollwyvl/4210809 to your computer and use it in GitHub Desktop.
Save bollwyvl/4210809 to your computer and use it in GitHub Desktop.
JavaScript Array.sample and Object.traverse
function sample(opts, num){
// like python sample
var choice,
choices = [];
while(choices.length < num && choices < opts.length){
choice = parseInt(Math.random() * opts.length);
if(choices.indexOf(choice) == -1){
choices.push(choice);
}
}
return choices.map(function(c){return opts[c]});
}
function traverse(item, axis, found){
/*
returns all items on the provided axis (named property)
memoization is attractive, but the immediate case wouldn't be
able to make use of it
*/
found = arguments.length == 2 ? [item] : found;
return item[axis]
.filter(function(item){
return !found || found.indexOf(item) == -1;
})
.reduce(function(found, item){
found.push(item);
return traverse(item, axis, found);
}, found)
}
// simple test data
var data = [];
for (var i=0; i<100; i++){
data.push({
id: i,
axis1: sample(data, parseInt(Math.random() * 3)),
axis2: sample(data, parseInt(Math.random() * 2)),
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment