Node.js 应用程序,编写验证测试。鉴于以下情况:
var obj = { foo: null, bar: null, baz: null},
values = [ 0, 1];
我需要创建 n 个对象来说明分配给每个属性的每个可能值的组合,以表示每个可能的用例。所以对于这个例子,输出应该是 2^3=8 个对象,例如
[
{ foo: 0, bar: 0, baz: 0},
{ foo: 0, bar: 1, baz: 0},
{ foo: 0, bar: 1, baz: 1},
{ foo: 0, bar: 0, baz: 1},
{ foo: 1, bar: 0, baz: 0},
{ foo: 1, bar: 1, baz: 0},
{ foo: 1, bar: 1, baz: 1},
{ foo: 1, bar: 0, baz: 1},
]
Underscore 或 lodash 或其他库是可接受的解决方案。理想情况下,我想要这样的东西:
var mapUseCases = function(current, remaining) {
// using Underscore, for example, pull the current case out of the
// possible cases, perform logic, then continue iterating through
// remaining cases
var result = current.map(function(item) {
// perform some kind of logic, idk
return magic(item);
});
return mapUseCases(result, _.without(remaining, current));
}
var myValidationHeadache = mapUseCases(currentThing, somethingElse);
请原谅我的伪代码,我想我伤了脑筋。 ¯\_(ツ)_/¯
最佳答案
任何对象长度和任何值的解决方案。
请注意,undefined
值不会显示。
function buildObjects(o) {
var keys = Object.keys(o),
result = [];
function x(p, tupel) {
o[keys[p]].forEach(function (a) {
if (p + 1 < keys.length) {
x(p + 1, tupel.concat(a));
} else {
result.push(tupel.concat(a).reduce(function (r, b, i) {
r[keys[i]] = b;
return r;
}, {}));
}
});
}
x(0, []);
return result;
}
document.write('<pre>' + JSON.stringify(buildObjects({
foo: [0, 1, 2],
bar: [true, false],
baz: [true, false, 0, 1, 42]
}), 0, 4) + '</pre>');
关于javascript - 为用例组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35513991/