hs96
hs96

Reputation: 79

Generating acronyms using JavaScript

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

Answers (1)

Trace
Trace

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:

  • If the current character is a letter check if boolean flag is false
  • If the boolean is false, add the character to the current acronym value
  • Set the boolean flag to true, so the other letters of the word will not be executed until a separator is found
  • Start from step 1 when a separator is found (non-alphabetic character).

So basically it just aggregates the first letters of every word into a new string.

Upvotes: 1

Related Questions