permutaciones javascript code example

Example 1: permutation javascript

const permutations = arr => {
  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
  return arr.reduce(
    (acc, item, i) =>
      acc.concat(
        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
          item,
          ...val,
        ])
      ),
    []
  );
};

Example 2: permutaciones con repeticion javascript

function permutator (input) {
  var set =[];
  function permute (arr, data) {
    var cur, memo = data || [];

    for (var i = 0; i < arr.length; i++) {
       cur = arr.splice(i, 1)[0];
       if (arr.length === 0) set.push(memo.concat([cur]));
       permute(arr.slice(), memo.concat([cur]));
       arr.splice(i, 0, cur);
    }
    return set;
 }
 return permute(input);
}