Created
December 5, 2012 00:48
-
-
Save bollwyvl/4210809 to your computer and use it in GitHub Desktop.
JavaScript Array.sample and Object.traverse
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
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