Skip to content

Instantly share code, notes, and snippets.

@qfox
Created June 30, 2016 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qfox/121fc1d20c8f77ddaa3fef91bfdf4bd7 to your computer and use it in GitHub Desktop.
Save qfox/121fc1d20c8f77ddaa3fef91bfdf4bd7 to your computer and use it in GitHub Desktop.
comb.js
module.exports = function comb(matrix) {
return Object.keys(matrix).reduce((res, k) => _fillIn(res, k, matrix[k]), [{}]);
/**
* Adds all combinations of existing array and incoming variants
* @param {Array<Object>} combinations - existing combinations
* @param {String} key - new key for items in combinations
* @param {Array} values - values for new key
* @returns {Array<Object>} - modified
*/
function _fillIn(combinations, key, values) {
var res = [];
combinations.forEach(function(obj) {
values.forEach(function(v) {
var _new = _clone(obj);
if (v !== undefined) _new[key] = v;
res.push(_new);
});
});
return res;
}
function _clone(old) {
var _new = {};
for (var k in old)
if (old.hasOwnProperty(k))
_new[k] = old[k];
return _new;
}
}
module.parent ||
console.log(require('util').inspect(comb({
kwas: ['1', '2', '3'],
shelest: ['1', '2'],
vobla: [undefined, 'defined']
})));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment