DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 90

The task is to implement a sum function.

The boilerplate code

function sum(num) {
  // your code here
}

Enter fullscreen mode Exit fullscreen mode

sum(num) returns a function that remembers the current total, can be called again to add more numbers, and can behave like a number when compared

function inner(next) {
 return sum(num + next)
}
Enter fullscreen mode Exit fullscreen mode

Each time the function is called, a new sum call is created and the previous value is not modified. JavaScript tries to convert objects to primitives during comparison. Since the result is a function, JS calls valueOf

inner.valueOf = function () {
  return num;
};
Enter fullscreen mode Exit fullscreen mode

Some environments use toString, so adding it to the function makes it more robust

inner.toString = function () {
  return String(num);
};
Enter fullscreen mode Exit fullscreen mode

The final code

 function inner(next) {
    return sum (num + next);
  }

  inner.valueOf = function () {
    return num;
  }

  inner.toString = function () {
    return String(num);
  }
  return inner;
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)