Hey everyone,
I have been pondering on recursion in the last day or two. I was looking for a way to get all possible combinations of the elements in an array and found a beautiful peace of code that does something similiar, but for a string:
function combinations(str) {
let fn = function(active, rest, a) {
if (active==0 && rest==0)
return;
if (rest==0) {
a.push(active);
} else {
fn(active + rest[0], rest.slice(1), a);
fn(active, rest.slice(1), a);
}
return a;
}
return fn("", str, []);
}
console.log(combinations(“abcde”));
Have been trying to understand how it works for like hours and I think I finally did, when i drew it out with a pen and paper. Real beauty!
I wanted to recreate this code for an array, but I get stuck on the way. I guess I have to get more basic knowledge on all array methods first, but I am not very patient with this one Can someone help please?