Combining arrays for use cases

后端 未结 3 1691
再見小時候
再見小時候 2021-01-06 23:13

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

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

I need to

3条回答
  •  广开言路
    2021-01-07 00:07

    This is a non-recursive version of what you want:

    function createRange(keys, values) {
      if (typeof values[0] !== typeof [])
        values = keys.map(k => values);
      var pointer = {};
      var repeats = 1;
      keys.forEach((k, i) => {
        var vLen = values[i].length;
        repeats *= vLen;
        pointer[k] = {
          get value() {
              return values[i][pointer[k].current]
            },
            current: 0,
            period: Math.pow(vLen, i),
            inc: function() {
              var ptr = pointer[k];
              ptr.current++;
              if (ptr.current < vLen) return;
    
              ptr.current = 0;
              if (i + 1 === keys.length) return;
    
              var nk = keys[i + 1];
              pointer[nk].inc()
            }
        };
      });
      var result = [];
      for (var i = 0; i < repeats; i++) {
        var o = {};
        result.push(o);
        keys.forEach(k => o[k] = pointer[k].value)
        pointer[keys[0]].inc();
      }
      return result;
    }
    
    var objKeys = ['u', 'v', 'w', 'x', 'y', 'z'];
    var objValues = [
      ['1', '2', '3'],
      ['a', 'b', 'c'],
      ['foo', 'bar', 'baz'],
      [1, 3, 2],
      ['test', 'try', 'catch'],
      ['Hello', 'World'],
    ];
    
    var range = createRange(objKeys, objValues);
    range.map(v => document.write(JSON.stringify(v).big()))

提交回复
热议问题