Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Last active February 18, 2016 07:10
Show Gist options
  • Save voltrevo/124d98ee6aac47029cbe to your computer and use it in GitHub Desktop.
Save voltrevo/124d98ee6aac47029cbe to your computer and use it in GitHub Desktop.
const enumerateChoices = (sets) => {
if (sets.length === 0) {
return [[]];
}
const subChoices = enumerateChoices(sets.slice(1));
return [].concat(...sets[0].map(
choice => subChoices.map(choices => [choice].concat(choices))
));
};
export default enumerateChoices;
@voltrevo
Copy link
Author

Example usage:

import enumerateChoices from './enumerateChoices.js';

const namedSets = {
  color: ['yellow', 'green', 'red'],
  fruit: ['banana', 'apple', 'rhubarb'],
  instrument: ['piano', 'flute', 'violin']
};

const sets = Object.keys(namedSets).map(name => namedSets[name]);

console.log(
  enumerateChoices(sets)
    .map(choices => choices.join(' '))
    .join('\n')
);

Output:

yellow banana piano
yellow banana flute
yellow banana violin
yellow apple piano
yellow apple flute
yellow apple violin
yellow rhubarb piano
yellow rhubarb flute
yellow rhubarb violin
green banana piano
green banana flute
green banana violin
green apple piano
green apple flute
green apple violin
green rhubarb piano
green rhubarb flute
green rhubarb violin
red banana piano
red banana flute
red banana violin
red apple piano
red apple flute
red apple violin
red rhubarb piano
red rhubarb flute
red rhubarb violin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment