如何用回调函数实现JavaScript中的sum(a)(b)(c)函数?
sum(a)(b)(c) Hey there! First off, your curried closure implementation is a perfectly valid way to achieve the sum(a)(b)(c) signature—it uses nested function closures to preserve the values of a and b until the final call with c. That said, let's break down what the interviewer might have meant by a "callback function approach."
What a Callback-Focused Implementation Might Look Like
The key here is to shift the summation logic into an explicit callback function, rather than calculating the sum directly in the innermost closure. This makes the summation logic modular and reusable, which is likely what the interviewer was aiming for.
Here's a clear implementation that aligns with the sum(a)(b)(c) signature while leveraging callback functions:
// Define a standalone callback function to handle the summation logic const calculateTotal = (num1, num2, num3) => num1 + num2 + num3; function sum(a) { return function(b) { return function(c) { // Instead of returning a + b + c directly, we delegate to the callback return calculateTotal(a, b, c); } } } // Test the function console.log(sum(2)(3)(4)); // Output: 9
A More Dynamic Callback Variant (If the Interviewer Wanted Custom Logic)
If the interviewer intended for the final step to accept a callback (to customize how the sum is processed), we can adjust the implementation while still keeping the core sum(a)(b)(c) structure (where c acts as the callback):
function sum(a) { return function(b) { return function(callback) { // Calculate the intermediate sum and pass it to the callback const partialSum = a + b; callback(partialSum); } } } // Usage example: add an extra value in the callback sum(1)(2)((partial) => { const finalSum = partial + 3; console.log(finalSum); // Output: 6 });
Why This Differs From Your Original Implementation
Your closure-based version relies on nested functions preserving the scope of a and b to compute the sum directly. The callback-focused approach extracts the core logic into a separate function (or uses a callback to handle the final result), making it easier to modify the summation behavior later—for example, you could swap calculateTotal for a function that averages the numbers without changing the nested structure of sum.
内容的提问来源于stack exchange,提问作者charul

