In this tutorial, we will see What Is A 用Javascript编写函数. Currying is an alteration of functions that turns a function from callable as f(a, b, c)
into callable as f(a)(b)(c)
.
用Javascript编写函数
currying函数是一个采用多个参数并将其转换为一次仅具有一个参数的函数序列的函数。
让我们看看它是如何完成的。因此,首先让我们考虑3个参数的基本乘法。
的JavaScript正常功能
// Normal definition
function multiply(a, b, c) {
return a * b * c;
};
console.log(multiply(1, 2, 4));
// Output: 8
上面的函数可以转换为咖喱函数,例如:
的JavaScript库里函数
// Simple curry function definition
function multiply(a) {
return (b) => {
return (c) => {
return a * b * c;
};
};
};
console.log(multiply(1)(2)(4));
// Output: 8
// ***** Short Hand Code *****
const multiply = (a) => (b) => (c) => a * b * c;
这样,n元函数变为一元函数,最后一个函数将所有参数的结果一起返回到函数中。
我们为什么要创建一个currying函数
要了解收益,我们需要真实的例子。
for example, we have a logging function log(date, importance, message)
that formats and outputs the information. in a real-life project, such functions have many useful features like sending logs over the network.
function log(date, importance, message) {
alert(`[${date.getHours()}: ${date.getMinutes()}] [${importance}] ${message}`);
}
让我们用咖喱 Lodash.
var curried = _.curry(log);
现在我们的日志可以以两种不同的方式工作。
// Normal Way : log(a, b, c)
log(new Date(), "DEBUGGING", "some message");
// Currying : log(a)(b)(c)
log(new Date())("DEBUGGING")("some message");
现在,我们可以轻松地为当前日志创建服务功能:
// logNow will be the partial of log with fixed first argument
let logNow = log(new Date());
// use it
logNow("ERROR", "message"); // [HH:mm:yyyy] ERROR message
Now, logNow
is a log
with the fixed first argument, in other words, “partially applied function” or “partial” for short.
我们可以更进一步,为当前的调试日志提供便利功能:
let debugNow = logNow("DEBUGGING");
debugNow("message"); // [HH:mm:yyyy] DEBUGGING message
- We didn’t lose anything after currying:
log
is still callable normally. - 我们可以轻松生成部分功能,例如今天的日志。
获取有关的更多教程 的JavaScript