javascript - 为用例组合数组

标签 javascript arrays node.js testing

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/

相关文章:

javascript - Angular Controller - 保存 Node 发送的接收文件

javascript - 获取嵌套对象的值

javascript - 从数组中生成 Angular reducer

php - MySQL bind_param 向表写入 NULL

arrays - 一维 “Square”数组中的旋转对称索引

node.js - 无法创建具有一对多关系的对象

javascript - jQuery 中奇怪的变量作用域

javascript - Knockout js 复选框点击功能问题

java - 在 Java 中将项目添加到数组开头的最简单方法

node.js - `mongoose` 如何处理添加具有 __NOT__ 部分架构的字段的文档?