0

I'm trying to solve the following problem on CodeWars: A Chain adding function:

We want to create a function that will add numbers together when called in succession.

add(1)(2);
// returns 3

We also want to be able to continue to add numbers to our chain.

add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

and so on.

A single call should return the number passed in.

 add(1); // 1

We should be able to store the returned values and reuse them.

var addTwo = add(2);
addTwo; // 2
addTwo + 5; // 7
addTwo(3); // 5
addTwo(3)(5); // 10

We can assume any number being passed in will be valid whole number.

I tried for many hours but to no avail. Like for eg.

add(1)(2)(4) <--- 3 chained functions 

I learned about what "currying" is but returning a function inside my main function would only satisfy add(1)(2) <-- 2 chained functions. Again, I'm trying to chain any number of functions here and I can't seem to figure it out.

If the sample test is add(5)(13)(3)(10)(5)(6)(20) that's 7 functions chained...I can't possibly type 7 functions in a row return inside one before another except for the first one (main function).

I would like to ask is there any way to check the length of chained functions? Aside from my question, I would appreciate some tips, I'm not asking for a full blown answer.

trincot
  • 317,000
  • 35
  • 244
  • 286
Dota100
  • 124
  • 4
  • 12
  • You can't check the "length" of the chain; nothing knows the length in the runtime, it's just a sequence of expressions being evaluated. – Pointy May 22 '21 at 17:38
  • You need Objec.prototype.valueOf(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf – loop May 22 '21 at 17:46
  • 1
    They are not asking to count the number of calls. They are just asking for the sum: [Variadic curried sum function](https://stackoverflow.com/questions/5832891) – adiga May 22 '21 at 17:47

1 Answers1

0

I can't possibly type 7 functions in a row return inside one before another

That is why you need to create a recursive solution, so that it can work for any chain length.

I should add that in order to solve this you must look really well at exactly what is tested. Here is one test:

Test.expect(add(1)(2)(3) == 6);

Pay special attention to the equality operator that is used. This should give you a hint at how it can be possible to return a value that can both serve for further chaining, and can be equal to a number at the same time.

Hint 1:

== is not the same kind of equality as ===

Hint 2:

valueOf

Hint 3:

Functions are objects. They can have custom properties like any other object.

Hint 4:

Make sure to return a function that has a custom valueOf method that returns the current sum value.

Hint 5:

Use a recursive call, passing it the sum of:
1. the argument passed to the outermost function call
2. the argument passed to the function that is returned

trincot
  • 317,000
  • 35
  • 244
  • 286