24
loading...
This website collects cookies to deliver better user experience
arity
.function multiply(a, b) {
// do sth
}
function _multiply(a, b, c) {
// do sth
}
multiply
takes two arguments (2-arity function) and _multiply
takes three arguments (3-arity function).function multiply(x,y,z) {
return x*y*z;
}
multiply(1,2,3); // 6
function multiply(x) {
return (y) => {
return (z) => {
return x * y * z
}
}
}
console.log(multiply(1)(2)(3)) // 6
const multi1 = multiply(1);
const multi2 = multi1(2);
const result = multi2(3);
console.log(result); // 6
let multi1 = multiply(1);
return (y) => {
return (z) => {
return x * y * z
}
}
multi1
holds the above function definition which takes an argument y
.multi1
function, passing in 2
:let multi2 = multi1(2);
return (z) => {
return x * y * z
}
multi2 = (z) => {
return x * y * z
}
const result = multi2(3);
console.log(result); // 6
z
variable but will perform the operation with other variables whose enclosing function scope has long since returned. Because of Closure
, it still functions🔥.function multiply(x) {
return (y) => {
return (z) => {
return x * y * z
}
}
}
let a = multiply(10);
a(3,12);
a(20,12);
a(20,13);
// OR
multiply(10)(3,12);
multiply(10)(20,12);
multiply(10)(20,13);
arity
.function multiply1(x, y, z) {
return multiply2(x,y,z)
}
// to
function multiply1(x) {
return (y,z) => {
return mulitply2(x,y,z)
}
}
function multiply1(x) {
return (y) = > {
return (z) = > {
return multiply2(x,y,z)
}
}
}
function currying(fn, ...args) {
return (..._arg) => {
return fn(...args, ..._arg);
}
}
function multiply(x,y,z) {
return x * y * z
}
let multi = currying(multiply,10);
multi(2,3); // 60
multi(1,4); // 40
Closure
makes currying possible in JavaScript. I hope you have learned something new about currying!