Skip to content

Instantly share code, notes, and snippets.

@cuipengfei
Last active December 31, 2015 08:19
Show Gist options
  • Save cuipengfei/7959425 to your computer and use it in GitHub Desktop.
Save cuipengfei/7959425 to your computer and use it in GitHub Desktop.
functional js implement reduce
module.exports = function reduce(arr, fn, initial) {
function justDoOne(index, value) {
if (index >= arr.length) {
return value
}
return justDoOne(index + 1, fn(value, arr[index]))
}
return justDoOne(0, initial)
}
function reduce(arr, fn, initial) {
return (function reduceOne(index, value) {
if (index > arr.length - 1) return value
return reduceOne(index + 1, fn(value, arr[index], index, arr))
})(0, initial)
}
module.exports = function reduce(arr, fn, initial) {
var acc = initial
arr.forEach(function(elem) {
acc = fn(acc, elem)
})
return acc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment