zoukankan      html  css  js  c++  java
  • js函数式编程-函数合并

    函数编程的函数组合:两个纯函数组合之后返回了一个新函数
    var compose = function(f,g) {
      return function(x) {
        return f(g(x));
      };
    };
    效果:
    var toUpperCase = function(x) {
    return x.toUpperCase();
    };
    var exclaim = function(x) {
    return x + "!";
    };
     
    var shout = compose(
    exclaim,
    toUpperCase
    );
     
    console.log(shout("hello world")); //HELLO WORLD!
    函数组合可以避免在实现相同需求式而使用嵌套函数,实现可读性。
    实现一组函数的叠加产生一个新的函数我们可以利用reduce来实现,利用reduce 的累加的特性实现函数的嵌套。
    function comp1(arr) {
       return function(val) {
         return arr.reduce(function(x, y) {
           return y(x(val));
         });
       };
    }
    或者
    function comp2(arr) {
       return function(val) {
          return arr.reduce(function(x, y) {
            return y(x);   
          },val);
       };
    }
     
    这里把需要组合的函数赋值给一个数组,然后返回一个函数对数组里的函数进行组合后的函数
    例子:
    var funArr = [toUpperCase, exclaim];
     
    console.log(comp1(funArr)); // function...
    console.log(comp1(funArr)("hello")); // HELLO!
     
    console.log(comp2(funArr)); // function...
    console.log(comp2(funArr)("hello")); // HELLO! 
  • 相关阅读:
    前缀和
    hdu6290奢侈的旅行
    make_pair
    New Year and Buggy Bot
    STL next_permutation 算法原理和自行实现
    前端面试题集合
    node设置cookie
    黑客与geek
    xss
    node async
  • 原文地址:https://www.cnblogs.com/chrissong/p/10390444.html
Copyright © 2011-2022 走看看