Combining arrays for use cases

后端 未结 3 1686
再見小時候
再見小時候 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-06 23:43

    One way is to count from "000" to "999" in a values.length-based system:

    keys = ['foo','bar','baz']
    values = ['A', 'B']
    
    
    width = keys.length
    base = values.length
    out = []
    
    for(var i = 0; i < Math.pow(base, width); i++) {
      
      var d = [], j = i;
      
      while(d.length < width) {
        d.unshift(j % base)
        j = Math.floor(j / base)
      }
      
      var p = {};
      
      for(var k = 0; k < width; k++)
        p[keys[k]] = values[d[k]]
    
      out.push(p)
    }  
    
    
    document.write('
    '+JSON.stringify(out,0,3))

    Update for products:

    'use strict';
    
    let
        keys = ['foo', 'bar', 'baz'],
        values = [
            ['A', 'B'],
            ['a', 'b', 'c'],
            [0, 1]
        ];
    
    
    let zip = (h, t) =>
        h.reduce((res, x) =>
            res.concat(t.map(y => [x].concat(y)))
        , []);
    
    let product = arrays => arrays.length
        ? zip(arrays[0], product(arrays.slice(1)))
        : [[]];
    
    let combine = (keys, values) =>
        keys.reduce((res, k, i) =>
            (res[k] = values[i], res)
            , {});
    
    let z = product(values).map(v => combine(keys, v));
    
    z.map(x => document.write('
    '+JSON.stringify(x)+'
    '))

提交回复
热议问题