I've created a Range
class that creates a generator function for iterating over a range of integers. My next step is to create a generator function that iterates all possible permutations of values for each property. Here is the simplified code for a hard-coded example:
// Create the parameter definitions (works perfectly).
const paramDef = {
propA: new Range(1, 2, 3), // [1,2,3] as iterator
propB: new Range(2, 4, 6) // [2,4,6] as iterator
};
// Hardcoded implementation (the goal is to make this generic/re-usable)
function* getUnits(def){
// Foreach value of propA...
for(let valPropA of def.propA.getValues()){
// and foreach value of propB...
for(let valPropB of def.propB.getValues()){
// Yield an instance with the current values...
yield {
propA: valPropA,
propB: valPropB
};
}
}
}
// Iterate one-by-one, creating a permutation of object properties.
for(let unit of getUnits(paramDef)){
console.log(unit);
}
// Outputs:
// {"propA":1,"propB":2}
// {"propA":1,"propB":4}
// {"propA":1,"propB":6}
// {"propA":2,"propB":2}
// {"propA":2,"propB":4}
// {"propA":2,"propB":6}
// {"propA":3,"propB":2}
// {"propA":3,"propB":4}
// {"propA":3,"propB":6}
I've tried a number of things, but the furthest I've gotten was to get the first iteration to return correctly, but nothing else. How do you generalize the getUnits()
function and what traps should I look out for?