javascriptstringsplitarray.prototype.map

Find the highest scoring word from a string according to its position in the alphabet using JavaScript


I am trying to solve CodeWars challenges but I have a problem with this one:

"Given a string of words, you need to find the highest scoring word. Each letter of a word scores points according to its position in the alphabet:

 a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string. If two words score the same, return the word that appears earliest in the original string. All letters will be lowercase and all inputs will be valid."

My code passed 104 cases but got wrong on 1 case. The wrong answer test case is

'what time are we climbing up the volcano' 

According to codewars - Expected: 'volcano', instead got: 'climbing'

Any ideas?

link of the problem - https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/javascript

 function high(x){
  let result = '', value =0, counterValue = 0; 

  let splittedArray = x.split(' ');

  splittedArray.map(splitItem => {
    counterValue = 0;

    let splitItemArray = splitItem.split('');

    splitItemArray.map(splitChar => { 
      counterValue += splitChar.charCodeAt();
    })

    if(counterValue>value){
      result = splitItem;
      value = counterValue;
    }
  });
  return result;
}

Solution

  • function high(x) {
      const words = x.split(' ');
      const alphabetMap = {};
      for (let i='a'.charCodeAt(), j = 1; i <= 'z'.charCodeAt(); i++, j++) {
        alphabetMap[i] = j;
      }
      let highestScoringWord = { word: '', score: 0 };
      words.forEach(w => {
        const chars = w.split('');
        const sumOfChars = chars.reduce((count, char) => count + alphabetMap[char.charCodeAt()], 0);
        if (sumOfChars > highestScoringWord.score) {
          highestScoringWord = { word: w, score: sumOfChars };
        }
      });
    
      return highestScoringWord.word;
    }
    
    console.log(high('what time are we climbing up the volcano')) // volcano ;)