Skip to content

Instantly share code, notes, and snippets.

@kubarskii
Created February 5, 2025 15:48
Show Gist options
  • Save kubarskii/9c153c17c855bab37695f1f3816685c3 to your computer and use it in GitHub Desktop.
Save kubarskii/9c153c17c855bab37695f1f3816685c3 to your computer and use it in GitHub Desktop.
Very simple JavaScript Reduce polyfill
/**
*
* @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