Given a function fn, return a curried version of that function.
A curried function is a function that accepts fewer or an equal number of parameters as the original function and returns either another curried function or the same value the original function would have returned.
In practical terms, if you called the original function like sum(1,2,3), you would call the curried version like csum(1)(2)(3), csum(1)(2,3), csum(1,2)(3), or csum(1,2,3). All these methods of calling the curried function should return the same value as the original.
給予一個函式 fn,回傳一個 curried function。 curried function 是一個函式,它接受與原始函數更少或相等的元素數量, 並返回另一個 curried function 或回傳與原始函式相等的值。 實際上,如果您呼叫原始函式 sum(1, 2, 3), 您可以呼叫 curried function 像這樣 csum(1)(2)(3), csum(1)(2, 3), csum(1, 2)(3), csum(1, 2, 3)。 所有這些呼叫 curried function 的模型都可以回傳與原始函式相同的值。
Example 1:
Input: fn = function sum(a, b, c) { return a + b + c; } inputs = [[1],[2],[3]] Output: 6
Example 2:
Input: fn = function sum(a, b, c) { return a + b + c; } inputs = [[1,2],[3]] Output: 6
Example 3:
Input: fn = function sum(a, b, c) { return a + b + c; } inputs = [[],[],[1,2,3]] Output: 6
Example 4:
Input: fn = function life() { return 42; } inputs = [[]] Output: 42
solution:
由題意可以知道以下四種呼叫參數的方式都需要可以完成執行:
1. csum(1)(2)(3) //6 2. csum(1)(2, 3) //6 3. csum(1, 2)(3) //6 4. csum(1, 2, 3) //6
我們試著宣告一個 nums 當作空的陣列[],並用來存放參數。
接著我們可以將 return function curried(…args){} 視為高階函數(High-order function),
也就是指可以接受函式作為參數或將函式作為結果返回的函式。
接下來,我們希望調用這個 curried function 來傳遞一個新的 curried function,
同時我們要判斷參數符合指定數量時回傳運算的結果。
ex. 在 curried function 內部,通過 fn.length 可以取得 sum 函式的形式的參數數量。
在 curried function 執行中,每次調用 csum 時,傳入的參數都被追加到 nums 陣列中。
當 nums 的長度等於 fn.length 時,表示已經接收到足夠的參數,可以調用原始的 sum 函式,並回傳計算結果。
Code 1: BigO(1)
var curry = function(fn) { let nums = [] return function curried(...args) { nums = [...nums, ...args] if (fn.length === nums.length) { const res = fn(...nums) nums = [] return res; } else { return curried; } }; };
FlowChart:
Example 1
function sum(a, b, c) { return a + b + c } const csum = curry(sum) console.log(csum(1)(2)(3))
Example 2
function sum(a, b, c) { return a + b + c } const csum = curry(sum) console.log(csum(1, 2)(3))
Example 3
function sum(a, b, c) { return a + b + c } const csum = curry(sum) console.log(csum()()(1, 2, 3))
Example 4
function lift() { return 42; } const csum = curry(lift) console.log(csum())