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') // 是否日期
  • 相关阅读:
    1017 A除以B (20分)**
    剑指 Offer 11. 旋转数组的最小数字(简单)
    剑指 Offer 04. 二维数组中的查找(中等)
    剑指 Offer 53
    剑指 Offer 53
    剑指 Offer 03. 数组中重复的数字(简单)
    剑指 Offer 58
    剑指 Offer 05. 替换空格(简单)
    执行npm install命令出错问题
    剑指 Offer 35. 复杂链表的复制(中等)
  • 原文地址:https://www.cnblogs.com/jxjl/p/12825258.html
Copyright © 2011-2022 走看看