Created
June 30, 2016 21:30
-
-
Save qfox/121fc1d20c8f77ddaa3fef91bfdf4bd7 to your computer and use it in GitHub Desktop.
comb.js
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
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