DEV Community

Alex Hernandez
Alex Hernandez

Posted on

JS Exercise: Sum of a String

Feeling confident in Javascript?

Well, given a string of lowercase letters, would you be able to sum them all up into 1 value?
In one line of code?

Solution and explanations are below.

The Solution

const lettersum = s =>
s
.split('')
.map(c => c.charCodeAt(0) - 96)
.reduce((a, b) => a + b, 0);

Pretty concise, isn't it?
Let's go over this step-by-step

JS Arrow functions

'const lettersum = s =>'

First, we use 'const' to declare a variable (named 'lettersum') whose value shouldn't change later.

Then we begin to declare a function using a compact definition called an 'arrow function expression'.

Splitting

s
.split('')

This is the same as s.split()
However, JS ignores newlines (line-terminators) when they separate bits of code (except in cases where it auto-inserts ';' like in return)

We do this so as we chain multiple functions, it stays easy to read

So what does 's.split('')' do?

Well, split() is a string method, that will divide the string into substrings, and returns them as an array.

In this case, '' means we want to divide the string at every character.

This gives us the string as an array of characters

Mapping

 .map(c => c.charCodeAt(0) - 96)

Map accepts a function and will return the array created from calling the function on every element in the array.

Here we are going through our array of characters, and turning each one into a digit, subtracting 96 so a=0.

Reduce

 .reduce((a, b) => a + b, 0);

Lastly, this reduces the list down to a single value.

It calls the function we pass on each item in the array, storing the result in 'a' and calling the function again with 'b' set as the next value in the array.

Here we are summing up every element in the list.

Closing

And that's it! So in summary, we

  • Split the string into characters
  • Go through each character, converting it into a number
  • Sum up all the numbers

Thanks for sticking around, and stay tuned for the next JS lesson.

Top comments (5)

Collapse
 
lexlohr profile image
Alex Lohr

An interesting property of alphabetic characters in almost all encodings is that they are organized in two hexadecimal rows both for lowercase and uppercase characters which allows you to just use an integer AND operator & 31 on them to get a number from 1 to 27.

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

It's more efficient to remove the map

const lettersum = s => [...s].reduce((a,b) => a + b.charCodeAt() - 96, 0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darkwiiplayer profile image
๐’ŽWii ๐Ÿณ๏ธโ€โšง๏ธ
Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

Interesting

Collapse
 
darkwiiplayer profile image
๐’ŽWii ๐Ÿณ๏ธโ€โšง๏ธ

I'm slightly confused about what you mean by "summing" the letters into one value. Letters aren't numbers, how would you add them together?