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
主题 StackJimmy 设计