1、柯里化函数
-
柯里化函数(Currying)定义:是把接受多个参数的函数变换成接受一个单一参数的函数**(最初函数的第一个参数)的函数,能夠返回接受余下的参数而且返回结果的新函数**的技术
-
作用:减少代码冗余,增加可读性
函数的柯里化,是 Javascript 中函数式编程的一个重要概念。它返回的,是一个函数的函数。
其实现方式,需要依赖参数以及递归,通过拆分参数的方式,来调用一个多参数的函数方法,以达到减少代码冗余,增加可读性的目的。
-
实现:
// 写一个 sum 方法,当使用下面的语法调用时,能正常工作 // console.log(sum(2, 3)); // Outputs 5 // console.log(sum(2)(3)); // Outputs 5 // 下面是接收多个参数的函数 function sum(a, b, c) { console.log(a + b + c); } // 柯里化 函数 // 函数 // 传入最后一个参数,本例代表c function curry(fn, lastValue) { return function (...args) { // args : 获取调用的函数的参数列表 if (lastValue) { // 判断最后参数是否有赋值 args = args.concat(lastValue) } // 判断参数的大小来决定传回一个函数还是直接调用函数 if (args.length < fn.length) { // 回调函数 return curry(fn, args) } else { // 直接调用 return fn.apply(null, args) } } } // 柯里化后 sum = curry(sum, [1]); sum(2, 3) sum(2)(3) sum(2, 2, 3) // sum(1, 2, 3); // 6 // sum(1, 2)(3); // 6 // sum(1)(2, 3); // 6 // sum(1)(2)(3); // 6
2、函数组合
-
函数组合(Function Composition)定义:函数组合是将多个函数合并为一个新函数的过程
-
作用:可以将多个要依次调用的函数合并为一个函数,从而避免了函数的嵌套调用
-
实现:
let fn1 = x => (x + 10) let fn2 = x => (x * 10) let fn3 = x => (x / 10) // 函数嵌套调用,导致代码可读性极差,且难以维护 console.log(fn3(fn1(fn2(fn1(5))))); // log:16 // ====================================================== function compose(...args) { // 1 获取长度 let len = args.length // 2 参数非函数跳出 let arr = [] args.forEach(fn => { if (typeof fn === 'function') { arr.push(fn) } }) // 3 返回出执行函数 return (x) => { if (len === 0) { return arr[0](x) } else if (len === 1) { return x } else if (len) { return arr.reduce((reg, fn2) => { // 第一次为函数,后面为参数 return typeof reg === 'function' ? fn2(reg(x)) : fn2(reg) }) } } } console.log(compose()(5)); console.log(compose(fn1)(5)); console.log(compose(fn1, fn2)(5)); console.log(compose(fn1, fn2, fn3)(5)); console.log(compose(fn1, fn2, fn3, fn1)(5));
3、函数链式调用
-
函数链式调用(Method Chaining)定义:在一个对象上连续调用多个方法,并且每个方法都返回该对象本身
-
作用:可以将多个函数调用连接在一起,从而减少嵌套层级
-
实现:
const calculator = { value: 0, add(num) { this.value += num; return this; }, subtract(num) { this.value -= num; return this; }, multiply(num) { this.value *= num; return this; }, divide(num) { this.value /= num; return this; }, getResult() { return this.value; } }; const result = calculator.add(5) .multiply(3) .subtract(2) .divide(4) .getResult(); console.log(result); // 输出: 2.5
关注公众号:前端兔 查看更多前端知识分享~~