Last active
April 26, 2018 08:35
-
-
Save nickangtc/65b1f5d34ffc79027919391fa1e0c918 to your computer and use it in GitHub Desktop.
Homemade version of the built-in forEach() and reduce() in JavaScript
This file contains 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
/** | |
* 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