问题描述
Node.js应用程序,编写验证测试.给出以下内容:
Node.js app, writing validation tests. Given the following:
var obj = { foo: null, bar: null, baz: null},
values = [ 0, 1];
我需要创建 n 个对象,以说明为每个属性分配的可能值的每种组合,以表示每种可能的用例.因此,对于此示例,输出应为 2 ^ 3 = 8 个对象,例如
I need to create n number of objects to account for every property being assigned every combination of possible values, to represent every possible use case. So for this example, the output should be 2^3=8 objects, e.g.
[
{ 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},
]
下划线或lodash或其他库是可接受的解决方案.理想情况下,我想要这样的东西:
Underscore or lodash or other libraries are acceptable solutions. Ideally, I would like something like so:
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);
请原谅我的伪代码,我想我很伤脑筋. ¯\ _(ツ)_/¯
Pardon my pseudocode, I think I broke my brain. ¯\_(ツ)_/¯
推荐答案
任何对象长度和任何值的解决方案.
Solution for any object length and any values.
请注意,undefined
值不会显示.
Please note, undefined
values do not show up.
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>');
这篇关于结合用例的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!