Skip to content

Instantly share code, notes, and snippets.

@oitee
Created April 4, 2022 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oitee/169425e332476b3ec952da323006eb57 to your computer and use it in GitHub Desktop.
Save oitee/169425e332476b3ec952da323006eb57 to your computer and use it in GitHub Desktop.
A JS implementation of powerSet, using tail recursion
//[...] =>[[], []]
// [] => [[]]
// [1] => [[], [1]]
// [1, 2] => [[], [1]] + [2] + [1, 2]
// [1, 2, 3] => [[], [1], [2], [1, 2]] + [3] + [1, 3] + [ 1, 2] + [1, 2, 3]
function powerSet(arr) {
if (arr.length === 0) {
return [[]];
}
let lastItem = arr.pop();
let res = powerSet(arr);
newRes = res.map((itemArr) => {
// this is to create a clone of the array to prevent mutation of the elements of the original array `res`
let currentArr = itemArr.slice();
currentArr.push(lastItem);
return currentArr;
});
return res.concat(newRes);
}
function powerSetTailRecursive(arr, acc = [[]]) {
if (arr.length === 0) {
return acc;
}
let lastItem = arr.pop();
let newAcc = acc.map(itemArr => {
let currentArr = itemArr.slice();
currentArr.push(lastItem)
return currentArr
})
newAcc = acc.concat(newAcc);
return powerSetTailRecursive(arr, newAcc);
}
console.log(powerSet([1, 2, 3]));
console.log(powerSetTailRecursive([1, 2, 3]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment