Created
February 11, 2019 19:06
-
-
Save MarcoPolo/5237aa035c4eaa9dec038dca8cd74cb2 to your computer and use it in GitHub Desktop.
Enumerate through props quickly
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 seedPossibilitiesCount(seed) { | |
if (Array.isArray(seed)) { | |
return seed.length | |
} else if (typeof seed === 'object' && !!seed && seed.constructor === Object) { | |
let count = 1 | |
Object.keys(seed).forEach(k => { | |
count *= seedPossibilitiesCount(seed[k]) | |
}) | |
return count | |
} | |
return 1 | |
} | |
function seedToProp(seed, iteration) { | |
if (Array.isArray(seed)) { | |
return seed[iteration % seed.length] | |
} else if (typeof seed === 'object' && !!seed && seed.constructor === Object) { | |
const prop = {} | |
let divisor = 1 | |
Object.keys(seed).map(k => { | |
const possibilityCounts = seedPossibilitiesCount(seed[k]) | |
const localIteration = Math.floor(iteration / divisor) % possibilityCounts | |
divisor *= possibilityCounts | |
prop[k] = seedToProp(seed[k], localIteration) | |
}) | |
return prop | |
} | |
return seed | |
} | |
function* allEnumerations(seed) { | |
for (let i = 0; i < seedPossibilitiesCount(seed); i++) { | |
yield seedToProp(seed, i) | |
} | |
} | |
// Demo | |
const BoolSeed = [true, false] | |
const TodoSeed = { | |
thing: 'Water Plant', | |
done: BoolSeed, | |
} | |
for (prop of allEnumerations(TodoSeed)) { | |
console.log(prop) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment