Last active
March 18, 2025 05:02
-
-
Save koozdra/bc68632d6728428e3a44 to your computer and use it in GitHub Desktop.
lodash factorial
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
// Imperetive: | |
function factorial(n) { | |
var result = 1; | |
for (var i = 1; i <= n; i++) { | |
result *= i | |
} | |
return result; | |
} | |
// Functional: | |
// (creates the array then reduces it) | |
function factorial(n) { | |
return _.range(1, n+1) | |
.reduce(function(p,i) { | |
return p*i; | |
}); | |
} | |
// Functional Better: | |
// (array creation and reduction done in one pass) | |
function factorial(n) { | |
return _(_.range(1, n+1)). | |
.reduce(function(p,i) {return p*i}) | |
.value(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment