ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ฟังก์ชันเรียกกลับและค่าเริ่มต้น
ฟังก์ชันควรสะสมค่าจากการวนซ้ำของอาร์เรย์ และสุดท้ายคืนค่าเหมือนที่ Array.prototype.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)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
15