Skip to content

Instantly share code, notes, and snippets.

@a-x-
Created April 15, 2016 21:10
Show Gist options
  • Select an option

  • Save a-x-/6f5e6cb175e395ea89df68164b1ea6d8 to your computer and use it in GitHub Desktop.

Select an option

Save a-x-/6f5e6cb175e395ea89df68164b1ea6d8 to your computer and use it in GitHub Desktop.
var cloneObj = obj => {
var newObj = {};
Object.keys(obj).forEach((key) => {
newObj[key] = obj[key];
});
return newObj;
};
var appendTrace = (trace, key, val) => {
var newTrace = cloneObj(trace);
newTrace[key] = val;
return newTrace;
};
var variateFab = obj => {
var keys = Object.keys(obj);
var l = keys.length;
var variate = (keyIndex, trace) => {
if (keyIndex >= l) return trace;
return obj[keys[keyIndex]].reduce((items, val) => {
return items.concat(variate(keyIndex + 1, appendTrace(trace, keys[keyIndex], val)));
}, []);
};
return variate;
};
function combinations(obj) {
return variateFab(obj)(0, {});
}
combinations({
color: ['red', 'green', 'blue'],
size: ['xl', 'm'],
lang: ['ru', 'ua', 'by', 'tr']
});
/*
[
{color: 'red', size: 'xl', lang: 'ru'},
{color: 'red', size: 'xl', lang: 'ua'},
{color: 'red', size: 'xl', lang: 'by'},
{color: 'red', size: 'xl', lang: 'tr'},
{color: 'red', size: 'm', lang: 'ru'},
...
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment