Mô tả vấn đề
Chúng ta cần viết hàm JavaScript nhận vào mảng, một hàm callback và giá trị khởi tạo. Hàm tích lũy giá trị qua vòng lặp mảng và trả về giá trị cuối, giống Array.prototype.reduce().
Ví dụ minh họa
Mã thực hiện (polyfill reduce):
const arr = [1, 2, 3, 4, 5];
const sum = (a, b) => a + b;
Array.prototype.customReduce = function(callback, initial){
if(!initial){
initial = this[0];
};
let res = initial;
for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){
res = callback(res, this[i]);
};
return res;
};
console.log(arr.customReduce(sum, 0));Đầu ra
Kết quả trong console:
15