Last active
December 31, 2015 08:19
-
-
Save cuipengfei/7959425 to your computer and use it in GitHub Desktop.
functional js implement reduce
This file contains hidden or 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
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) | |
} |
This file contains hidden or 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
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) | |
} |
This file contains hidden or 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
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