|
| 1 | +// Digit Sum |
| 2 | +// Write a function that takes a string and parses out all the numbers and adds them together |
| 3 | + |
| 4 | +// **** BEST SOLUTION AT THE BOTTOM **** |
| 5 | + |
| 6 | +const digitSum = str => { |
| 7 | + return str |
| 8 | + .split(' ') |
| 9 | + .map(word => { |
| 10 | + return word |
| 11 | + .split('') |
| 12 | + .filter(char => { |
| 13 | + return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].includes(parseInt(char)) |
| 14 | + }) |
| 15 | + .join('') |
| 16 | + }) |
| 17 | + .reduce((acc, num) => { |
| 18 | + if (num) { |
| 19 | + return acc + parseInt(num) |
| 20 | + } |
| 21 | + return acc |
| 22 | + }, 0) |
| 23 | +} |
| 24 | + |
| 25 | +console.log(digitSum('2 apples, 12 oranges')) |
| 26 | +console.log(digitSum('3 and 20ish apples')) |
| 27 | +console.log(digitSum('1234')) |
| 28 | +console.log(digitSum('No nums in here')) |
| 29 | + |
| 30 | +// |
| 31 | +// |
| 32 | +// or using a regex (turn string into array, remove all letters and special characters, then sum up values left in array) |
| 33 | +const digitSumRegex = str => { |
| 34 | + return str |
| 35 | + .split(' ') |
| 36 | + .map(word => { |
| 37 | + return word.replace(/[\W_A-Z]/gi, '') |
| 38 | + }) |
| 39 | + .reduce((acc, num) => { |
| 40 | + // if not an empty string |
| 41 | + if (num) { |
| 42 | + return acc + parseInt(num) |
| 43 | + } |
| 44 | + return acc |
| 45 | + }, 0) |
| 46 | +} |
| 47 | + |
| 48 | +console.log(digitSumRegex('2 apples, 12 oranges')) |
| 49 | +console.log(digitSumRegex('3!! apples && 20ish Oranges!')) |
| 50 | +console.log(digitSumRegex('1234')) |
| 51 | +console.log(digitSumRegex('No nums in here')) |
| 52 | + |
| 53 | +// |
| 54 | +// |
| 55 | +// another regex option |
| 56 | +const digitSumRegex2 = str => { |
| 57 | + // need to have the '|| []' 'or blank array' b/c otherwise 'null' is returned |
| 58 | + const nums = str.match(/\d+/g) || [] |
| 59 | + return nums.reduce((acc, num) => { |
| 60 | + return acc + parseInt(num) |
| 61 | + }, 0) |
| 62 | +} |
| 63 | + |
| 64 | +console.log(digitSumRegex2('2 apples, 12 oranges')) |
| 65 | +console.log(digitSumRegex2('3!! apples && 20ish Oranges!')) |
| 66 | +console.log(digitSumRegex2('1234')) |
| 67 | +console.log(digitSumRegex2('No nums in here')) |
0 commit comments