Created
January 31, 2023 13:28
-
-
Save zArubaru/d0f8e0ba322c22c523c2ab0cb32a7ce4 to your computer and use it in GitHub Desktop.
Thriv Times 1/2023
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
// Short answer, which fails on erroneous input. | |
const sumOfEveryOther = number => | |
number.toString().match(/\d/g) | |
.reduce( | |
(result, currentNumber, currentIndex) => | |
currentIndex % 2 | |
? result + +currentNumber | |
: result | |
, 0); | |
// Longer answers checks that the input value is correct... | |
const sumOfEveryOther = number => { | |
if (!Number.isFinite(number)) { | |
throw new Error('Passed value not a finite number'); | |
} | |
// .. and double checks that the match does not return null. | |
return (number.toString().match(/\d/g) || []) | |
.reduce( | |
(result, currentNumber, currentIndex) => | |
currentIndex % 2 | |
? result + +currentNumber | |
: result | |
, 0) | |
} | |
// sumOfEveryOther(123456789) // 20 | |
// sumOfEveryOther(10) // 0 | |
// sumOfEveryOther(1010.11) // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment