Reputation: 79
This code below with its function to generate acronyms was extracted from Stanford Uni's lecture notes. The code checks for every character and correctly handles strings that have leading, trailing, or multiple spaces, or even hyphens. However, I have difficulty understanding a line of code.
function acronym(str) {
let result = "";
let inWord = false;
for (let i = 0; i < str.length; i++) {
let ch = str.charAt(i);
if (isLetter(ch)) {
if (!inWord) result += ch;
inWord = true;
} else {
inWord = false;
}
}
return result;
}
function isLetter(ch) {
return ch.length === 1 &&
ALPHABET.indexOf(ch.toUpperCase()) !== -1;
}
As shown in the code above, I'm not quite sure how the "inWord" variable works. I'm not sure how it sets word boundaries that are indicated by sequences of nonletters. If you don't mind, can someone please enlighten me?
Your help is much appreciated. Thanks!
Upvotes: 0
Views: 406
Reputation: 18899
The code tries to make an acronym, i.e. take the first letter of every word to create to create a new word.
Translation of the loop:
So basically it just aggregates the first letters of every word into a new string.
Upvotes: 1