JS Exercise: Sum of a String

I'm a software developer in the Los Angeles area. I build web and fullstack applications, as well as participate in cybersecurity games (HTB, Vulnhub, OTW, etc).
Search for a command to run...

I'm a software developer in the Los Angeles area. I build web and fullstack applications, as well as participate in cybersecurity games (HTB, Vulnhub, OTW, etc).
No comments yet. Be the first to comment.
How long does it take to send a message through an entire organization.

Want to learn how to solve Leetcode problem 10: Regular Expression Matching, using GoLang? Then follow along as I explain how to implement regex matching in Golang. What is Dynamic Programming (DP)? Dynamic programming is a problem-solving approach u...

How long does it take to send a message through an entire organization.

Finding the maximum path sum in a Binary Tree.

How to Serialize and Deserialize a Binary Search Tree

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.
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
'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'.
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
.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((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.
And that's it! So in summary, we
Thanks for sticking around, and stay tuned for the next JS lesson.