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);
      };
    }
  • 相关阅读:
    pip 8 安装
    zabbix server配置文件
    双代号网络图、双代号时标网络图
    logrotate
    tsql 执行存储过程
    dos 加用户
    Visual Studio (VS IDE) 你必须知道的功能和技巧
    格式化数字字符串 与C#变量
    .NET中的字符串你了解多少?
    新手如何有效地学习.NET
  • 原文地址:https://www.cnblogs.com/myspecialzone/p/13949976.html
Copyright © 2011-2022 走看看