组合用例的数组

kmu*_*nky 2 javascript arrays testing node.js

Node.js应用程序,编写验证测试.鉴于以下内容:

var obj = { foo: null, bar: null, baz: null},
    values = [ 0, 1];
Run Code Online (Sandbox Code Playgroud)

我需要创建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},
]
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

请原谅我的伪代码,我想我的脑子已经坏了.¯\ _(ツ)_ /¯

Nin*_*olz 11

任何对象长度和任何值的解决方案.

请注意,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>');
Run Code Online (Sandbox Code Playgroud)