zoukankan      html  css  js  c++  java
  • js函数组合

    一.概念

         函数组合顾名思义就是将两个或两个以上函数组合成一个新函数例如:

        

    const composeFunction=function(f1,f2){
       return function(args){
          return f1(f2(args))   
       }   
    }
    //f1,f2是都是函数,args是组合后生成的新函数的参数

    二.函数组合的作用

        我们在实际开发项目的时候,通常都会将函数设计得尽量职责单一,比如有以下三个功能

        比较单一得函数分别是lowerCase(变成小写),upperCase(变成大写),trim(去除空格),split(转换成数组)

    function lowerCase(input) {
    return input && typeof input === "string" ? input.toLowerCase() : input;
    }

    function upperCase(input) {
    return input && typeof input === "string" ? input.toUpperCase() : input;
    }

    function trim(input) {
    return typeof input === "string" ? input.trim() : input;
    }

    function split(input, delimiter = ",") {
    return typeof input === "string" ? input.split(delimiter) : input;
    }

    // compose函数的实现,请参考 “组合函数的实现” 部分。
    const trimLowerCaseAndSplit = compose(trim, lowerCase, split);
    trimLowerCaseAndSplit(" a,B,C "); // ["a", "b", "c"]

    三.函数组合的实现

    function compose(...funcs) {
      return function (x) {
        return funcs.reduce(function (arg, fn) {
          return fn(arg);
        }, x);
      };
    }
  • 相关阅读:
    html页面自适应宽度
    Angularjs Select获取数组下标
    spring boot集成mybatis分页插件
    百度分享实现https
    nginx自定义错误页面
    nginx代理tomcat
    Nginx配置SSL证书
    Nginx安装
    xmlns:amq="http://activemq.apache.org/schema/core"报错
    ActiveMQ
  • 原文地址:https://www.cnblogs.com/myspecialzone/p/13949976.html
Copyright © 2011-2022 走看看