vendredi 19 février 2016

Combining arrays for use cases

Node.js app, writing validation tests. Given the following:

var obj = { foo: null, bar: null, baz: null},
    values = [ 0, 1];

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},
]

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. ¯_(ツ)_/¯

Aucun commentaire:

Enregistrer un commentaire