TikTok / VO Interview Question: Implement a Chainable sum() Function

17 Views
No Comments

Q: Implement sum() so that the following expressions evaluate correctly:

sum(1, 2, 3).sumOf(); // 6
sum(2, 3)(2).sumOf(); // 7
sum(1)(2)(3)(4).sumOf(); // 10
sum(2)(4, 1)(2).sumOf(); // 9

This problem asks you to design a chainable <code>sum()</code> function whose return value can keep accepting numbers across multiple calls and finally expose the total through <code>sumOf()</code>. The key idea is to use a closure to store the running total, while returning a callable function so the chain can continue. It is a classic JavaScript interview question about closures, function objects, and API design.

END
 0