手撕算法(1)——数组API

50 阅读1分钟
Array.prototype.myForEach = function(fn) {
    for (const item of this) {
        fn(item);
    }
}

Array.prototype.myMap = function(fn) {
    const res = [];
    for (const item of this) {
        res.push(fn(item));
    }
    return res;
}

Array.prototype.myFind = function(fn) {
    for (const item of this) {
        if (fn(item)) return item;
    }
    return undefined;
}

Array.prototype.myFilter = function(fn) {
    const res = [];
    for (const item of this) {
        if (fn(item)) res.push(item);
    }
    return res;
}

Array.prototype.mySome = function(fn) {
    for (const item of this) {
        if (fn(item)) return true;
    }
    return false;
}

Array.prototype.myEvery = function(fn) {
    for (const item of this) {
        if (!fn(item)) return false;
    }
    return true;
}
// 用例:
const arr = [1, 2, 3, 4, 5];

arr.myForEach((item) => {
    console.log(item);  // 1  // 2  // 3  // 4  // 5
});

const doubledArray = arr.myMap((item) => {
    return item * 2;
});
console.log(doubledArray);  // [2, 4, 6, 8, 10]

const foundItem = arr.myFind((item) => {
    return item > 2;
});
console.log(foundItem);  // 3

const filteredArray = arr.myFilter((item) => {
    return item % 2 === 0;
});
console.log(filteredArray);  // [2, 4]

const hasEvenNumber = arr.mySome((item) => {
    return item % 2 === 0;
});
console.log(hasEvenNumber);  // true

const allEvenNumbers = arr.myEvery((item) => {
    return item % 2 === 0;
});
console.log(allEvenNumbers);  // false