zoukankan      html  css  js  c++  java
  • 闭包的运用之-----函数柯里化

     什么是函数柯里化

    • 对于普通函数来说:我们传入不同的参数,通常会做一些运算逻辑,返回其运算后的结果或状态。
    function add(x, y){
      return x + y
    }
    add(1, 2) // 3
    • 对于柯里化:函数返回是一个新函数, 接收参数只是为了构造出新函数
    function sayInfo(name){
      return function (age){ 
          console.log(`${name}今年${age}岁`)
      }  
    }
    const johnAge = sayInfo('John')  // 等价于====> const johnAge = function (age){console.log(`John今年${age}岁`)}
    const tomAge = sayInfo('Tom')    // 等价于====> const tomAge = function (age){console.log(`Tom今年${age}岁`)}
    johnAge('12') // John今年12岁
    johnAge('13') // John今年13岁
    tomAge('22') // Tom今年22岁
    tomAge('22') // Tom今年23岁

    如果不用柯里化应该是这样写代码:

    function sayInfo(name, age){
       console.log(`${name}今年${age}岁`)
    }
    sayInfo('John', '12') // John今年12岁
    sayInfo('John', '13') // John今年13岁
    sayInfo('Tom', '22') // Tom今年22岁
    sayInfo('Tom', '22') // Tom今年23岁

    在这里看起来柯里化的代码反而显得冗余。其实不然, 下面看一个适合使用柯里化的场景。

    柯里化的运用

    1. 业务场景
    // 判断变量val是否是数组
    if(Object.prototype.toString.call(val).slice(8, -1) === 'Array'){
      ...
    }
    // 判断变量val是否是对象
    if(Object.prototype.toString.call(val).slice(8, -1) === 'Object'){
      ...
    }

            2.柯里化产生不同函数:

    // 上述代码判断使用的是同一个方法。可以用柯里化封装成不同函数
    const isType = function (type) {
      return function (val){
       return type === Object.prototype.toString.call(val).slice(8, -1)
     }
    }
    const isArray = isType('Array')
    const isObject = isType('Object')

            3.使用:

    // 由此,判断逻辑就改成如下形式
    if(isArray(val)){
        ...
    }
    if(isObject(val)){
        ...
    }
    // 修改后的代码精致了不少,不是吗?

    拓展:上述代码其实可以判断的类型很多。

    const isType = type => val => type === Object.prototype.toString.call(val).slice(8, -1)  // 箭头函数写法
    const isArray = isType('Array') // 是否数组
    const isObject = isType('Object') // 是否对象
    const isNull = isType('Null') // 是否null
    const isUndefined = isType('Undefined') // 是否undefined
    const isFunction = isType('Function') // 是否函数
    const isRegExp = isType('RegExp') // 是否正则
    const isString = isType('String') // 是否字符串
    const isNumber = isType('Number') // 是否数字
    const isDate = isType('Date') // 是否日期
  • 相关阅读:
    清除陷入CLOSE_WAIT的进程
    Eclipse
    远程连接elasticsearch遇到的问题
    Linux环境Nginx安装
    CentOS安装mysql
    py2exe使用方法
    Python3.4如何读写Excel
    getPhysicalNumberOfCells 与 getLastCellNum的区别
    浅析MySQL中exists与in的使用
    【MongoDB for Java】Java操作MongoDB
  • 原文地址:https://www.cnblogs.com/jxjl/p/12825258.html
Copyright © 2011-2022 走看看