grammarArticle method

  1. @useResult
String grammarArticle()

Returns the appropriate indefinite article ('a' or 'an') for this word, or an empty string if input is empty.

Uses English grammar heuristics for silent 'h', "you"-sound words, and vowel/consonant detection.

Example:

'apple'.grammarArticle(); // 'an'
'hour'.grammarArticle(); // 'an' (silent h)
'user'.grammarArticle(); // 'a' (you-sound)
'university'.grammarArticle(); // 'a'
'one-time'.grammarArticle(); // 'a'

Implementation

@useResult
String grammarArticle() {
  if (isEmpty) {
    return '';
  }

  final String word = trim();
  if (word.isEmpty) {
    return '';
  }

  final String lower = word.toLowerCase();

  // Phonetic exceptions are checked before the spelling-based vowel rule because
  // the article depends on pronunciation, not the first letter: "an hour"
  // (silent h), "a user" (consonant "y" sound), "a one-time" ("w" sound).
  if (_silentHPrefixes.any(lower.startsWith)) {
    return 'an';
  }

  if (_youSoundPrefixes.any(lower.startsWith)) {
    return 'a';
  }

  if (lower.startsWith(_wunSoundPrefix)) {
    return 'a';
  }

  // Fallback: vowel-initial words take "an", everything else "a".
  return switch (lower[0]) {
    'a' || 'e' || 'i' || 'o' || 'u' => 'an',
    _ => 'a',
  };
}