手写JS高阶函数

113 阅读1分钟

map

Array.prototype.map = function (callback, args) {
    if (this === null) {
        throw new TypeError("can not read property 'map' of null")
    }
    if (this === undefined) {
        throw new TypeError("can not read property 'map' of undefined")
    }
    if (Object.prototype.toString.call(callback) !== "[object Function]") {
        throw new TypeError(callback + " is not a function")
    }
    let Obj = Object(this)
    let T = args
    let length = Obj.length >>> 0
    let Arr = new Array(length)
    for (let i = 0; i < length; i++) {
        if (i in Obj) {
            let value = Obj[i]
            let mapValue = callback.call(T, value, i, Obj)
            Arr[i] = mapValue
        }
    }
    return Arr
}

reduce

Array.prototype.reduce = function (callback, initialValue) {
    if (this === null) {
        throw new TypeError("Cannot read perproty 'reduce' of null");
    }
    if (this === undefined) {
        throw new TypeError("Cannot read perproty 'reduce' of undefined");
    }
    // 回调类型异常判断
    if (Object.prototype.toString.call(callback) != '[object Function]') {
        throw new TypeError(callback + ' is not a function');
    }
    let Arr = Object(this);
    let len = Arr.length >>> 0;
    let i = 0;
    let accu = initialValue;
    outer: if (accu === undefined) {
        for (; i < len; i++) {
            if (i in Arr) {
                accu = Arr[i];
                i++;
                break outer;
            }
        }
        throw new Error('Eacy element of this array is empty');
    }
    for (; i < len; i++) {
        if (i in Arr) {
            accu = callback.call(undefined, accu, arr[i], Arr);
        }
    }
    return accu;
}