[NEW] A clearer, more readable return statement (#35565)

* A clearer, more readable return statement

Use .filter() to get the odd values in array.
Use .reduce() to sum.

Two separate tasks, one line, easier to read and understand.
Updated comments and Code Explanation accordingly.
This commit is contained in:
sidiousvic
2019-04-12 21:29:47 +09:00
committed by Oliver Eyton-Williams
parent a114b8939b
commit 7f845c1d2f

View File

@@ -80,7 +80,7 @@ As you get the next odd one, don't forget to add it to a global variable that ca
// Create an array of fib numbers till num
const arrFib = [1, 1];
let nextFib = 0;
// We put the new Fibonacci numbers to the front so we
// don't need to calculate the length of the array on each
// iteration
@@ -88,11 +88,8 @@ As you get the next odd one, don't forget to add it to a global variable that ca
arrFib.unshift(nextFib);
}
// Sum only the odd numbers and return the value
// First, reverse the array to avoid starting acc with the first/greater number when it's even
return arrFib.reverse().reduce((acc, curr) => {
return acc + curr * (curr % 2);
}, 0);
// We filter the array to get the odd numbers and reduce them to get their sum.
return arrFib.filter(x => x % 2 != 0).reduce((a, b) => a + b);
}
// test here
@@ -103,15 +100,19 @@ As you get the next odd one, don't forget to add it to a global variable that ca
### Code Explanation:
* Create an array of fibonacci numbers till **num**.
* Use `reduce()` method to find the sum of odd members of array.
* Use `filter()` method to filter out even numbers.
* Use `reduce()` method to sum the remaining (odd) values.
* Return the sum.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>JS Array Prototype Push</a>
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>JS For Loops Explained</a>
* <a href='https://www.freecodecamp.org/forum/t/javascript-array-prototype-filter/14289' target='_blank' rel='nofollow'>JS Array Prototype Filter</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299' target='_blank' rel='nofollow'>JS Array Prototype Reduce</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.