When I look at this problem and break it down to an algorithm, here is what I come up with:
I need to track both the current highest score of all words and the position of that word in the string.
I start by splitting the string by the space character to obtain the list of words, assigning a value of 0
to the current highest score and a value of 0
for the highest scoring word index (the first word).
Next, I look at each word and calculate a score for it. This calculation is done by looking at each letter and getting its value based on the assumption that an “a” is 1 and “z” is 26 and then create a running sum of these values.
Next, I compare the running sum of the word’s letters with the current highest score so far. If it is greater than the current highest score, I update the current highest score to be the running sum and update the position in the string to position of the current word in the string (use zero-index position).
Once I have looked at all the words, I return the word based on the position (the highest scoring word index).
That is it.
Next I code my algorithm two ways:
function high(str){
let highestScore = 0;
let highestScoreWordIndex = 0;
const wordArray = str.split(" ");
for(let i = 0; i < wordArray.length; i++){
let currentWordScore = 0;
for (let j = 0; j < wordArray[i].length; j++) {
currentWordScore += wordArray[i][j].toUpperCase().charCodeAt() - 64;
}
if (currentWordScore > highestScore) {
highestScore = currentWordScore;
highestScoreWordIndex = i;
}
}
return wordArray[highestScoreWordIndex];
}
or using a more functional approach:
function high(str) {
const wordArray = str.split(" ");
const highestScoreWordIndex = wordArray
.reduce((highest, word, i) => {
const currentWordScore = [...word]
.reduce((wordScore, letter) => wordScore + letter.toUpperCase().charCodeAt() - 64, 0);
return currentWordScore > highest.highestScore
? { highestScore: currentWordScore, highestIndex: i }
: highest;
}, { highestScore: 0, highestIndex: 0 }).highestIndex;
return wordArray[highestScoreWordIndex];
}