Is it possible to add a value when returning a function from a recursive function being chained?

65 views Asked by At

I'm attempting to make a recursive function that adds number values, and returns itself. Here's what I have so far.

const recursivo = (...v) => v ? v.reduce((a,e) => a + e, 0) + recursivo : 0;

Typical test cases may look like recursivo(1,2,3)(4,5)(6) or recursivo(100) or recursivo(12,34,56).

The function is broken because it returns a number value along with the function, but it doesn't get called on the next argument set. (makes sense)

Is it possible to add a value to a function that may be called on a chained argument set? For example something like the following:

const recursivo = (x,...v) => v ? recursivo(x + v.reduce((a,e) => a + e, 0),"?") : x;

This also doesn't work because the syntax is incorrect, though the question mark after the comma is just a placeholder since I'm not sure what the proper syntax could look like; it's representative of the next argument set in the chain.

If it's actually possible, how would I be able to write a recursive function that takes a sum and continues to call itself on an arbitrary number of chained arguments, adding a number to the next argument(s) that it will be calling itself on? (Doesn't necessarily have to be in ES6 syntax)

EDIT: This is not a duplicate of the linked SO post, though it is related. That post does not address the issue of handling argument sets that may consist of more than one argument, and the solutions proposed in that post also do not address this issue.

In other words, the solutions brought up in that post work for inputs like recursivo(1)(2)(3), but not like recursivo(1)(2,3,5)(4,5,7,8,24,156).

FINAL EDIT: Finally found a working solution, posted below:

function curryo(...v){
    let sum = 0;
    const fn = (...x) => (sum += x.reduce((a,e) => a + e, 0), fn);
    fn.valueOf = _ => sum;
    return fn(...v);
}

Changed the function name as it's related to currying rather than recursion. Removed recursion tag and added currying tag.

0

There are 0 answers