柯里化-写抽象函数

    技术2022-07-11  114

    函数柯里化,反柯里化

    判断变量的类型

    常用的判断类型的方法有四种:

    1.typeof 不能判断对象类型

    2.constructor 可以找到这个变量是通过谁构造出来的

    3.instanceOf 判断谁是谁的实例 _proto_

    4.Object.prototype.toString.call() 缺陷不能区分谁是谁的实例

    写个方法判断类型

    function isType(type, value) { 

        return Object.prototype.toString.call(value) === `[object ${type}]`

    }

    console.log(isType([], 'Array')

    能不能把方法进行细化,=> isString isArray

    function isType(type) { 

        return function (value) {

            Object.prototype.toString.call(value) === `[object ${type}]`

       }

    }

    let isArray = isType('Array');

    isArray('hello');

    通过一个柯里化函数,实现通用的柯里化方法

    const currying = (fn, arr = []) => {

        let len =  fn.length; // 这里获取的是函数的参数的个数

        return function (..args) {

            arr = [...arr, ...args];

            if(arr.length < len) {

                return curring(fn, arr);  //  递归不停的产生函数

           } else {

                return fn(...arr);

          }

        }

    }

    let isArray = curring(isType)('Array');

    console.log(isArray([]));

     

    例sum(a, b, c, d, e, f){ return a+b+c+d+e+f }

    let r = curring(sum)(1,2)(3,4)(5)(6)

     

    Processed: 0.015, SQL: 10