如何在 JavaScript 中將一個函式解除 Curry 化到 n 深度?


在 JavaScript 中,如果一個函式採用一個或多個引數,並返回一個預期剩餘引數的新函式,則認為該函式已“Curry 化”。Curry 化是一種強大的技術,可用於從現有函式建立新函式,或將一個函式解除 Curry 化到深度 n。

為什麼我們解除函式的 Curry 化?

有幾個原因可能導致你想要解除一個函式的 Curry 化。例如,你可能希望:−

  • 在預期非 Curry 化函式的環境中使用 Curry 化函式

  • 為了使其更容易閱讀或除錯,將 Curry 化函式轉換為非 Curry 化形式

  • 最佳化 Curry 化函式以提高效能

如何解除函式的 Curry 化?

有兩種方法可以解除一個函式的 Curry 化 −

  • 第一種方法是使用 “Function.prototype.apply” 方法。

  • 第二種方法是使用 “Function.prototype.call” 方法。

使用 “Function.prototype.apply” 方法

“Function.prototype.apply” 方法可用於解除一個函式的 Curry 化,直到深度 n。要執行此操作,你只需將 “this” 值和一個引數陣列傳遞給 "apply" 方法即可。例如:−

<!doctype html> <html> <head> <title>Examples</title> </head> <body> <p>uncurry up to depth 2 using Function apply() method</p> <div id="result"></div> <script> function add(a, b) { return a + b; } function curriedAdd(a) { return function(b) { return a + b; } } // Uncurry the "curriedAdd" function up to depth 2: document.getElementById("result").innerHTML = curriedAdd.apply(null, [1]).apply(null, [2]); // 3 </script> </body> </html>

使用 “Function.prototype.call” 方法

“Function.prototype.call” 方法也可用於解除一個函式的 Curry 化,直到深度 n。"call" 方法類似於 "apply" 方法,但你將 "this" 值和引數作為單獨的引數傳遞給 "call" 方法,而不是作為陣列。例如:−

<!doctype html> <html> <head> <title>Examples</title> </head> <body> <p> uncurry up to depth 2 using Function call() method</p> <div id="result"></div> <script> function add(a, b) { return a + b; } function curriedAdd(a) { return function(b) { return parseInt(a) + parseInt(b); } } // Uncurry the "curriedAdd" function up to depth 2: document.getElementById("result").innerHTML = curriedAdd.call(null, [1]).call(null, [2]); // 3 </script> </body> </html>

在上面的示例中,我們使用了 “call” 方法解除 “curriedAdd” 函式的 Curry 化。如你所見,“call” 方法比 “apply” 方法稍微冗長一些,但它們具有相同的效果。

使用“Function.prototype.apply”方法有什麼好處?

使用"Function.prototype.apply"方法來取消對函式的 currying 有以下幾個好處 -

  • “apply”方法比“call”方法速度更快。

  • “apply”方法比“call”方法得到更廣泛的支援。

  • “apply”方法比“call”方法更簡潔。

總之,Currying 是一種強大的技術,可用於從現有函式建立新函式或將函式取消 currying 直到深度 n。

更新日期:2022-08-04

133 人檢視

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告