Featured image of post 【JavaScript 函式】Currying 柯里化

【JavaScript 函式】Currying 柯里化

【JavaScript 函式】Currying 柯里化

Photo by Mohammad Rahmani on Unsplash

什麼是 Currying(柯里化)

Currying(柯里化),又稱為 parital applicationpartial evaluation

將一個 接受 n 個參數 的 function,轉變成 n 個只接受一個參數的 function」的過程

將一個接收複數參數的函式轉為一連串接收單一參數的函式

好處

  • 簡化參數的處理,基本上是一次處理一個參數,藉以提高程式的彈性和可讀性
  • 將程式碼依功能拆解成更細的片段,有助於重複利用

範例

乘法 Currying

原始乘法

function multiply(x, y){
  return x * y;
}

let result = multiply(3, 5);
// 15
console.log(result);

乘法 Currying(柯里化)後會變成

function curriedMultiply(x) {
  return function(y) {
    return x * y;
  }
}

let result = curriedMultiply(3)(5);
// 15
console.log(result);

Currying 話後傳入第一個參數會回傳內部函式,並將原本的參數帶入,所以可以直接在繼續呼叫取得運算的結果

function curriedMultiply(3) {
  return function(y) {
    return 3 * y;
  }
}

curriedMultiply(3) = function(y) {
  return 3 * y;
};

加法 Currying

原始加法

function tripleAdd(num1, num2, num3) {
  return num1 + num2 + num3
}

加法 Currying(柯里化)後會變成

function curriedTripleAdd(num1) {
    return function (num2) {
        return function (num3) {
            return (num1 + num2 + num3)}
    }
}
let result = curriedTripleAdd(10)(20)(30);
// 60
console.log(result);

Currying(柯里化)好處

暫存運算資料

function curriedMultiply(x) {
    return function(y) {
        return x * y;
    }
}

let curriedMultiplyBase7 = curriedMultiply(7);
let result1 = curriedMultiplyBase7(3);
let result2 = curriedMultiplyBase7(5);
let result3 = curriedMultiplyBase7(7);
// 7*3 = 21
console.log(result1);
// 7*5 = 35
console.log(result2);
// 7*7 = 49
console.log(result3);

參考資料

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy