Skip to content

Instantly share code, notes, and snippets.

@ggondim
Forked from miguelfrias/array-permutation.js
Last active October 20, 2017 01:37
Show Gist options
  • Save ggondim/1b5d781c04b875ca3331f51af2f44f62 to your computer and use it in GitHub Desktop.
Save ggondim/1b5d781c04b875ca3331f51af2f44f62 to your computer and use it in GitHub Desktop.
function permutation(collection) {
let current;
let result = [];
const currentArray = [];
const newResultArray = [];
if (collection.length) {
current = collection.shift();
result = permutation(collection);
currentArray.push(current);
result.map((list) => {
newResultArray.push(list.slice(0));
list.push(current);
});
result.push(currentArray);
result = result.concat(newResultArray);
}
return result;
}
console.log(permutation(['a','b','c','d'])
.join('\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment