Skip to content

Instantly share code, notes, and snippets.

@koozdra
Last active March 18, 2025 05:02
Show Gist options
  • Save koozdra/bc68632d6728428e3a44 to your computer and use it in GitHub Desktop.
Save koozdra/bc68632d6728428e3a44 to your computer and use it in GitHub Desktop.
lodash factorial
// 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