avatar

目录
JavaScript之函数式编程
  1. 纯函数:无副作用(不改变参数,不依赖环境,不进行请求,I/O操作);如map, slice等;

  2. 声明式代码

    javascript
    1
    2
    3
    4
    5
    6
    7
    // 命令式
    const makes = [];
    for (let i = 0; i < cars.length; i++) {
    makes.push(cars[i].make);
    }
    // 声明式
    const makes = cars.map(function(car){ return car.make; });
  3. 函数柯里化

    javascript
    1
    2
    3
    4
    5
    6
    7
    8
    // 普通写法
    const add = function(x, y) {
    return x + y;
    }
    // curry
    const addCurry = x => y => (x + y);
    const addTen = addCurry(10);
    const num = addTen(1);
  4. 函数组合

    javascript
    1
    2
    3
    4
    5
    6
    7
    8
    9
    const toUpperCase = x => x.toUpperCase();
    const exclaim = x => x + '!';
    // 普通
    const shout = x => exclaim(toUpperCase(x));
    console.log(shout('what happened!'));
    // 函数组合
    const compose = (...funcList) => x => funcList.reduce((pre, cur) => cur(pre), x);
    const shoutCompose = compose(toUpperCase, exclaim);
    console.log(shoutCompose('what happened!'));
  5. Point Free:函数无须提及将要操作的数据是什么样的

    javascript
    1
    2
    3
    4
    5
    6
    // 非 pointfree,因为提到了数据:word
    const snakeCase = function (word) {
    return word.toLowerCase().replace(/\s+/ig, '_');
    };
    // pointfree
    const snakeCase = compose(replace(/\s+/ig, '_'), toLowerCase);
文章作者: 盛顺炎
文章链接: https://www.shengshunyan.xyz/2018/10/25/JavaScript%E4%B9%8B%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 果实的技术分享
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论