pluralize static method

String pluralize(
  1. String word
)

Attempts to make a word plural using common English pluralization rules.

This is a basic implementation and won't handle all irregular plurals or complex cases perfectly. It avoids pluralizing words that already seem to be plural (basic check for ending in 's').

Rules applied:

  • Words ending in 'y' preceded by a consonant: y -> ies (e.g., story -> stories).
  • Words ending in 'y' preceded by a vowel: add s (e.g., boy -> boys).
  • Words ending in s, x, z, ch, sh: add es (e.g., box -> boxes).
  • Default: add s (e.g., cat -> cats).

Example:

StringUtils.pluralize("story") // "stories"
StringUtils.pluralize("box") // "boxes"
StringUtils.pluralize("cat") // "cats"
StringUtils.pluralize("statuses") // "statuses" (no change)

Implementation

static String pluralize(String word) {
  if (word.isEmpty) {
    return word;
  }

  final lowerWord = word.toLowerCase();

  // Rule: Don't pluralize if already ends in 's' (basic check)
  if (lowerWord.endsWith('s')) {
    return word;
  }

  // Add specific irregular plurals here if needed
  // Example:
  // if (lowerWord == 'person') return 'people';
  // if (lowerWord == 'child') return 'children';
  // if (lowerWord == 'man') return 'men';
  // if (lowerWord == 'woman') return 'women';
  // if (lowerWord == 'mouse') return 'mice';
  // if (lowerWord == 'goose') return 'geese';
  // if (lowerWord == 'foot') return 'feet';
  // if (lowerWord == 'tooth') return 'teeth';

  // Rule: Words ending in 'y' preceded by a consonant -> 'ies'
  if (lowerWord.endsWith('y')) {
    if (word.length > 1 &&
        !'aeiou'.contains(lowerWord[lowerWord.length - 2])) {
      return '${word.substring(0, word.length - 1)}ies';
    } else {
      // If 'y' is preceded by a vowel, just add 's' (e.g., boy -> boys)
      return '${word}s';
    }
  }

  // Rule: Words ending in 's', 'x', 'z', 'ch', 'sh' -> add 'es'
  if (lowerWord.endsWith('s') ||
      lowerWord.endsWith('x') ||
      lowerWord.endsWith('z') ||
      lowerWord.endsWith('ch') ||
      lowerWord.endsWith('sh')) {
    return '${word}es';
  }

  // Default rule: Add 's'
  return '${word}s';
}