reduce

Array.prototype.myReduce = function(fn,initVal){
    if(typeof fn !== 'function'){
        throw Error('Type Error')
    }

    const arr = this;
    if(arguments.length < 2 && arr.length === 0){
        throw new TypeError('Reduce of empty array with no initial value')
    }

    let res;
    let index;
    if(arguments.length > 1){
        res = initVal;
        index = 0;
    } else{
        res = arr[0];
        index = 1;
    }
    for(let i = index; i < arr.length; i++){
        res = fn(res,arr[i],i,arr);
    }
    return res;
}

const arr = [1,2,3];

const res = arr.myReduce((pre,cur,index,arr) => {
    console.log('pre',pre,'cur',cur,'index',index)
    console.log('arr',arr)
    return pre + cur
})

map

Array.prototype.myMap = function(fn){
    if(typeof fn !== 'function'){
        throw Error('Type Error')
    }

    const arr = this;
    const newArr = [];
    for(let i = 0; i < arr.length; i++){
        newArr.push(fn(arr[i], i));
    }
    return newArr;
}

const arr = [1];

const res = arr.myMap((item,index) => {

    return item + index;
})
console.log(res)

flat

Array.prototype.myFlat = function(depth) {
    const arr = this;
    if(depth > 0){
        return arr.reduce((pre,cur) => {
            return pre.concat(Array.isArray(cur) ? cur.myFlat(depth - 1) : cur)
        },[])
    }
    return arr;
}

const arr = [1,2,[3,4,[5,6]],[7,8]];
const res = arr.myFlat(1)
console.log(res)