Last active
May 17, 2016 23:38
-
-
Save drKnoxy/9f354301d21095afac37a48377c42dbe to your computer and use it in GitHub Desktop.
Using recursion to make an array of all product options
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
var options = [ | |
["red", "blue", "green", "yellow"], // color | |
["small", "medium", "large"], // size | |
["heavy", "light"], // thickness | |
]; | |
scope.inventory = findPermutations(options); | |
////////////////////// | |
function findPermutations(options) { | |
var resp = []; | |
if (options.length){ | |
recur(options); // kick off the recursion | |
} | |
return resp; | |
//////////////// | |
function recur(choices, aggr) { | |
var aggr = aggr || []; // aggregator | |
// We hit the bottom of our recursion | |
if (!choices.length) { | |
// write out to outer variable | |
resp.push(aggr); | |
return aggr; | |
} | |
// always loop over the first item we are given | |
for (var c = 0; c < choices[0].length; c++) { | |
// remove the first option and pass it back in | |
// pass the remaining choices | |
recur(choices.slice(1), aggr.concat(choices[0][c])); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment