rec takes 3 arguments : 'sum' - which in this case acts kind of like the accumulator in a reduce function.
'ar' - which is the current array to work on, starts off as the given array
'n' - maximum number of elements a combination could have
The rec function could be split into 2 parts :
'base case' - You return if n==0 meaning, you finished dealing with a combination of size 'n', and have it's accumulated sum. In that case, you just push your sum to the 'arr' variable.
'recursive case' - The heart of the recursion is in the for loop. What it basically does is call the function again, adding the current variable you are on to the sum, then basically slicing the array without that number you added, and of course decreasing n, because you only want groups of n size.
So each time, you add your number to the sum, then continue with the next number in groups of 3. This way he doesn't have duplicates. every time a single group finishes (from the very last bottom group) the function goes up and makes the other groups.
for example : if ar = [10, 25, 12, 20, 1], n = 3
you enter the for loop and call your function again:
i = 0; i < 5 ; i++
rec(0 + 10, [25, 12, 20, 1], 3-1)
You are still on the for loop so you continue until n = 0:
--i = 0; i < 4 ; i++
--rec(10 + 25, [12, 20, 1], 2-1)
----i = 0; i < 3 ; i++
----rec(35 + 12, [20, 1], 1-1)
------// here you reach the if statement, push the sum which is 47 and return
------arr = ;
----// now you are back here
----i = 1; i < 3 ; i++
----rec(35 + 20, [20, 1], 1-1)
------arr = [47, 55];
----i = 2; i < 3 ; i++
----rec(35 + 1, [20, 1], 1-1)
------arr = [47, 55, 36];
--i = 1; i < 4 ; i++
--rec(10 + 12, [12, 20, 1], 2-1)
// It continues like this until the first loop we got into finishes. So it goes from the inner most for loop (the botom one) back up to the first one so everytime it just sums the value with the rest of the values up to 3 to make all possible unique combination and store their sum.
Immutability is hip for a reason: not having side effects prevents bugs.
I'd argue that Array.prototype.sort's purpose is not returning a value; its purpose is sorting its argument in place ( probably for performance reasons ), and therefore should not return a value as well - it should have one effect and not two. People tend to use something.sort() directly and forget this also sorts something in place, often leading to bugs.
This comment is hidden because it contains spoiler information about the solution
Nice solution showing the power of reduce.
This code looks like an apartment building LOL.
Nice educational kata.
I couldn't figure out from the description what I'm supposed to do.
Nice usage of template literals.
It's just a kata about creating a silly syntactic sugar, IMO.