Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(guide): Add a new solution using reduce to "Factorialize a Number" #36629

Merged
merged 1 commit into from
Aug 20, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,28 @@ factorialize(5);

* <a href='https://www.geeksforgeeks.org/tail-recursion/' target='_blank' rel='nofollow'>Tail Recursion</a>
</details>

<details><summary>Solution 4 (Click to Show/Hide)</summary>

```js
function factorialize(num, factorial = 1) {
return num < 0 ? 1 : (
new Array(num).fill(undefined)
.reduce((product,val, index) => product * (index + 1), 1)
);
}

factorialize(5);
```

#### Code Explanation
* In this solution, we used "reduce" function to find the factorial value of the number. This is an intermadiate example.

* We have created an array which has length `num`. And we filled all elements of the array as `undefined`. In this case, we have to do this because empty arrays couldn't reducible. You can fill the array as your wish by the way. This depends on your engineering sight completely.

* In `reduce` function's accumulator is calling `product` this is also our final value. We are multiplying our index value with the product to find `factorial` value.

* We're setting product's initial value to 1 because if it was zero products gets zero always.

* Also the factorial value can't calculate for negative numbers, first of all, we're testing this.
</details>