Javascript Array permutations()

Description

Javascript Array permutations()


"use strict";//w w  w.ja  v  a2  s. c o  m

Array.prototype.permutations = function Array_permutations() {
    if (this.length === 1) {
        return [this];
    }
    var permutations = [],
        tmp, fixed;
    for (var i=0; i<this.length; i++) {
        tmp = this.slice();
        fixed = tmp.splice(i, 1);
        tmp.permutations().forEach(function(partial){
            partial.unshift(fixed[0]);
            permutations.push(partial);
        });
    }
    return permutations;
};



PreviousNext

Related