Array.prototype.myForEach = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
const arr = [1, 2, 3, 4, 5];
arr.myForEach((value, index, array) => {
console.log(`Value: ${value}, Index: ${index}, Array: ${array}`);
});
Array.prototype.myMap = function (callback) {
const newArray = [];
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i], i, this));
}
return newArray;
};
const arr = [1, 2, 3, 4, 5];
const squaredArr = arr.myMap((value, index, array) => {
return value * value;
});
console.log(squaredArr);
Array.prototype.myFilter = function (callback) {
const newArray = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
newArray.push(this[i]);
}
}
return newArray;
};
const arr = [1, 2, 3, 4, 5];
const evenArr = arr.myFilter((value, index, array) => {
return value % 2 === 0;
});
console.log(evenArr);
Array.prototype.mySome = function (callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return true;
}
}
return false;
};
const arr = [1, 2, 3, 4, 5];
const hasEven = arr.mySome((value, index, array) => {
return value % 2 === 0;
});
console.log(hasEven);
Array.prototype.myEvery = function (callback) {
for (let i = 0; i < this.length; i++) {
if (!callback(this[i], i, this)) {
return false;
}
}
return true;
};
const arr = [1, 2, 3, 4, 5];
const allEven = arr.myEvery((value, index, array) => {
return value % 2 === 0;
});
console.log(allEven);
Array.prototype.myReduce = function (callback, initialValue) {
let accumulator = initialValue === undefined ? this[0] : initialValue;
for (let i = 0; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};
const arr = [1, 2, 3, 4, 5];
const sum = arr.myReduce((accumulator, value, index, array) => {
return accumulator + value;
}, 0);
console.log(sum);
const str = "(()()())";
const balanced = str.split("").reduce((acc, cur) => {
if (cur === "(") {
acc++;
} else if (cur === ")") {
acc--;
}
return acc;
}, 0) === 0;
console.log(balanced);
Array.prototype.mySlice = function (startIndex, endIndex) {
const newArray = [];
const length = this.length;
const start = startIndex === undefined ? 0 : (startIndex >= 0 ? startIndex : length + startIndex);
const end = endIndex === undefined ? length : (endIndex >= 0 ? endIndex : length + endIndex);
const finalStart = Math.max(0, Math.min(length, start));
const finalEnd = Math.max(0, Math.min(length, end));
for (let i = finalStart; i < finalEnd; i++) {
newArray.push(this[i]);
}
return newArray;
};
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.mySlice(1, 4);
console.log(slicedArr);
const arr = [1, 2, 3, 4, 5];
const deletedItems = arr.splice(2, 2);
console.log(arr);
console.log(deletedItems);
arr.splice(2, 0, 6, 7);
console.log(arr);
arr.splice(2, 1, 8, 9);
console.log(arr);