DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on


#21 - Sum of integers in string CodeWars Kata (7 kyu)


Your task in this kata is to implement a function that calculates the sum of the integers inside a string.

For example:

Input --> "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog"
Output --> 3635.

My solution:

function sumOfIntegersInString(s){
  return s
    .map(x => parseInt(x) )
    .reduce((acc,el)=> acc+el,0)
Enter fullscreen mode Exit fullscreen mode


First I splitted the string using a regex that matches the elements that are not numbers, so everytime an element is not a number it'll split.

Input --> 'h3ll0w0rld'

Output --> ['', 'h', '3', '1', '', 'l', '0', 'w', '0', 'r', '', 'l', '', 'd', '']

After that I converted every string element in the array to a number

Input --> ['', 'h', '3', '1', '', 'l', '0', 'w', '0', 'r', '', 'l', '', 'd', '']

Output --> [NaN, NaN, 3, NaN, NaN, NaN, 0, NaN, 0, NaN, NaN, NaN, NaN, NaN, NaN]

After that I filtered the array and I used Boolean so I would get every falsy element removed

Input --> [NaN, NaN, 3, 1, NaN, NaN, 0, NaN, 0, NaN, NaN, NaN, NaN, NaN, NaN]

Output --> [3,1]

At the end I just used .reduce() so I could sum all of the numbers left in the array

Input --> [3,1]

Output --> 4

What do you think about this solution? ๐Ÿ‘‡๐Ÿค”

My Github
My twitter
Solve this Kata

Top comments (0)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but itโ€™s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!