Skip to content

Instantly share code, notes, and snippets.

@zArubaru
Created January 31, 2023 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zArubaru/d0f8e0ba322c22c523c2ab0cb32a7ce4 to your computer and use it in GitHub Desktop.
Save zArubaru/d0f8e0ba322c22c523c2ab0cb32a7ce4 to your computer and use it in GitHub Desktop.
Thriv Times 1/2023
// 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