Created
February 5, 2025 15:48
-
-
Save kubarskii/9c153c17c855bab37695f1f3816685c3 to your computer and use it in GitHub Desktop.
Very simple JavaScript Reduce polyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @param {(acc: any, curr: any, index: number, list:) => any} cb | |
* @returns {any} | |
*/ | |
function myReduce(cb, initialValue) { | |
const arr = this; | |
let acc = initialValue; | |
for (let i = 0; i < arr.length; i++) { | |
acc = cb(acc, arr[i], i, arr); | |
} | |
return acc; | |
} | |
Array.prototype.myReduce = myReduce; | |
const arr = [1, 2, 3, 4, 5]; | |
const sum = arr.myReduce((acc, curr) => acc + curr, 0); | |
console.log(sum); | |
const arr2 = [1, 2, 3, 4, 5]; | |
const sum2 = arr2.myReduce((acc, curr) => { | |
return acc | |
.then(() => new Promise((res) => setTimeout(() => res(curr), 1000))) | |
.then(console.log); | |
}, Promise.resolve(0)); | |
sum2.then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment