将CharCodeAt与索引而非句子一起使用



这个问题以前有不同的提问方式,但与本次不同。我想通过使用ES5或ES6编写一个函数来实现,该函数使用system A = 1, B = 2, C = 3 etc.计算得分最高的单词。字符串中单词之间只包含一个空格,并且没有标点符号。

我想出了这个函数。

var wordScoreCalculator = s =>
s.toLowerCase().
split('').
map(s => s.charCodeAt(0)-0x60).
filter(c => 1 <= c && c <= 26).
reduce((x,y) => x+y, 0);
wordScoreCalculator('I live in this world');

目前,charCodeAt正在对整个句子进行映射,并将所有单词一起计算到208。

我想让它与索引一起工作,这样它就可以单独计算每个单词,并只显示最高分数。

在这种情况下,它应该显示72。如何做到这一点?

非常感谢!

您需要额外映射每个单词,首先在空间上进行拆分。此外,因为根据条件The string will only contain a single space between words and there will be no punctuation,不需要filter,因为听起来单词总是包含字母字符:

var wordScoreCalculator = s =>
s.toLowerCase()
.split(' ')
.map(word => word
.split('')
.map(char => char.charCodeAt(0)-0x60)
.reduce((x,y) => x+y, 0)
)
.reduce((a, b) => Math.max(a, b))
console.log(wordScoreCalculator('I live in this world'));
console.log(wordScoreCalculator('I live in this world zzzz'));

或者,为了更好的可读性,可以将将将单词映射到其值的操作抽象为自己的函数:

const wordToScore = word => word
.split('')
.map(char => char.charCodeAt(0)-0x60)
.reduce((x,y) => x+y, 0);
const bestWordCalculator = s =>
s.toLowerCase()
.split(' ')
.map(wordToScore)
.reduce((a, b) => Math.max(a, b));

console.log(bestWordCalculator('I live in this world'));
console.log(bestWordCalculator('I live in this world zzzz'));

最新更新