Skip to content

Instantly share code, notes, and snippets.

@nickangtc
Last active April 26, 2018 08:35
Show Gist options
  • Save nickangtc/65b1f5d34ffc79027919391fa1e0c918 to your computer and use it in GitHub Desktop.
Save nickangtc/65b1f5d34ffc79027919391fa1e0c918 to your computer and use it in GitHub Desktop.
Homemade version of the built-in forEach() and reduce() in JavaScript
/**
* each()
*
* Apply an action to every item in an array.
*/
const list = [1, 2, 3];
const each = function (array, action) {
for (let i = 0; i < array.length; i++) {
action(array[i]);
}
}
each(list, function (item) {
console.log(`The item is: ${item}`);
});
//=> The item is: 1
//=> The item is: 2
//=> The item is: 3
/**
* reduce()
*
* Reduce an array to a single value by repetitively invoking a reducer function
* on each item in the array, returning the final value.
*
* Makes use of the above each() function.
*/
const reduce = function (array, reducer, accumulator) {
each(array, function (item) {
accumulator = reducer(accumulator, item);
});
return accumulator;
};
const sum = reduce(numbers, function (total, number) {
return total + number;
}, 0);
console.log(`Sum: ${sum}`); //=> 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment