All combinations of arrays in javascript

by Trevor Dixon

JavaScript

function cartesianCall(func, args) {
    var combos = allCombos.apply(this, args);
    
    for (var i = 0; i < combos.length; i++) {
        func.apply(null, combos[i]);
    }
}

function allCombos(first) {
    var isArray = toString.call(first) === "[object Array]";
    if (!isArray) first = [first]; // Convert non-array to an array with the value
                                   // as the only element
    else if (first.length === 0) first = [undefined]; // Convert empty array to an
                                                      // array with undefined as
                                                      // the only element

    if (arguments.length === 1) return first; // base case for recursion
    
    var result = [],
        rest = allCombos.apply(this, Array.prototype.slice.call(arguments, 1));
    
    for (var i = 0; i < first.length; i++) {
        for (var j = 0; j < rest.length; j++) {
            result.push([first[i]].concat(rest[j]));
        }
    }
    
    return result;
}

function printArgs() { console.log('Called with arguments:', arguments); }

cartesianCall(printArgs, [
    [true, false],
    undefined,
    [1, 2],
    [],
    'a string',
    ['a', 'b', 'c']
])