Lodash _.curry() 方法
Lodash _.curry()方法返回给定函数的柯里化版本。如果相反,参数将从右到左处理。
句法:
_.curry( fun, reverse )
参数:此方法采用上面列出并在下面讨论的两个参数。
- fun:这是给定的函数。
- reverse:它是一个可选参数,决定参数是否反转。
返回值:它返回函数的柯里化版本。
注意:要执行以下示例,您必须使用此命令提示符安装lodash-contrib库并执行以下命令。
npm install lodash-contrib
示例 1:
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function
function fun(a, b, c, d){
return a + b + c + d;
}
// Making curried function
var gfgFunc = _.curry(fun);
// Only operates for arguments same
// as the number in function
console.log("Addition is :",
gfgFunc(42)(23)(20)(30));
// Not adds for less arguments
console.log(gfgFunc(1)(2)(3));
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function
function fun(a, b, c){
return a * b * c;
}
// Making curried function
var gfgFunc = _.curry(fun);
// Only operates for arguments same
// as the number in function
console.log("Multiplication is :",
gfgFunc(20)(23)(27));
// Not multiplies for less arguments
console.log(gfgFunc(1)(2));
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function
function fun(a, b, c) {
return arguments;
}
// Making curried function
var gfgFunc = _.curry(fun, false);
// Only operates for arguments same
// as the number in function
console.log("curried arguments are :",
gfgFunc("arg1","arg2","arg3"));
输出:
Addition is : 115
[Function: wrapper]
示例 2:
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function
function fun(a, b, c){
return a * b * c;
}
// Making curried function
var gfgFunc = _.curry(fun);
// Only operates for arguments same
// as the number in function
console.log("Multiplication is :",
gfgFunc(20)(23)(27));
// Not multiplies for less arguments
console.log(gfgFunc(1)(2));
输出:
Multiplication is : 12420
[Function: wrapper]
示例 3:从左到右处理 reversed = false 的参数。
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function
function fun(a, b, c) {
return arguments;
}
// Making curried function
var gfgFunc = _.curry(fun, false);
// Only operates for arguments same
// as the number in function
console.log("curried arguments are :",
gfgFunc("arg1","arg2","arg3"));
输出:
curried arguments are : [Arguments]
{ '0': 'arg1', '1': 'arg2', '2': 'arg3' }