multiply(10)()()()(12) This a function call and we have to make a function to multiply 2 numbers
You can curry the function and leverage rest parameters and spreading . If there are no arguments supplied then (...args)
will be an empty array and .bind(this, ...args)
will create a function without partially applying any values to it.
Once all arguments are satisfied, the function is immediately called.
const curry = f => function(...args) { if (f.length - args.length <= 0) return f.apply(this, args); return curry(f.bind(this, ...args)); } const mul = (a, b) => a * b; const multiply = curry(mul); console.log(multiply(10, 12)); // = 120 console.log(multiply(10)(12)); // = 120 console.log(multiply(10)()(12)); // = 120 console.log(multiply(10)()()()(12)); // = 120 const obj = { x: 2, multiply: curry(function(a, b) { return a * b * this.x; }) } console.log(obj.multiply(10)()()()(12)); // = 240
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.