Skip to content

Instantly share code, notes, and snippets.

@texora
Last active June 19, 2020 05:16
Show Gist options
  • Save texora/6be2c267da8c35733d26c38a8f25df6d to your computer and use it in GitHub Desktop.
Save texora/6be2c267da8c35733d26c38a8f25df6d to your computer and use it in GitHub Desktop.
const _ = {};
_.reduce = (list, callback, initialValue) => {
let storage = initialValue; // 0 => 1 => 3 => 6 => 10
for (let i = 0; i < list.length; i++) { // 0 => 1 => 2 => 3
if (i === 0 && storage === undefined) {
storage = list[0];
} else {
storage = callback(list[i], storage); // (1 + 0) => (2 + 1) => (3 + 3) => (4 + 6)
}
}
return storage; // 10
}
_.reduce([1,2,3,4], (value, sum) => value + sum, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment