digitSumDifference
with Carmen Salas • 2024/11/04
Code Challenge
Using methods...
/*
## PEDAC
**Problem**
Parse a number into individual digits and output the difference between the sum of all evens and all odds.
Number -> Number indicating the difference (as described above)
**Examples/Edge Cases:**
2134 -> 6 (evens) - 4 (odds) == 2
**Data Structure**
- Number
- String
- Array
**Algorithm**
1. Convert number into string.
2. Split string into array.
3. Convert each item into a number.
4. Look at each number in the array: if even, add value to sum, else subtract value from sum.
*/
function solution(n) {
// method approach
return [...String(n)] // step 1 and 2
.reduce((sum, val) => // step 3 and 4
// loose equality for type conversion
(val%2 == 0) ? sum+Number(val) : sum-Number(val), 0);
}Simple no-method approach
Last updated