View Javadoc
1   package lv.id.jc.piglatin.core;
2   
3   import java.util.function.UnaryOperator;
4   import java.util.regex.Pattern;
5   
6   import org.springframework.stereotype.Component;
7   
8   /**
9    * This class is responsible for translating words to Pig Latin.
10   */
11  @Component("wordTranslator")
12  public class WordTranslator implements UnaryOperator<String> {
13      private static final Pattern RULES = Pattern.compile("""
14          (?:
15              (?<vowel>[aeiou]|xr|yt)
16              |
17              (?<consonant>y?(?:[^aeiouy]*qu|[^aeiouy]*))
18          )
19          (?<body>.*)
20          """, Pattern.CASE_INSENSITIVE | Pattern.COMMENTS
21      );
22      private static final String TEMPLATE = "${vowel}${body}${consonant}ay";
23  
24      /**
25       * Translates a word to Pig Latin.
26       *
27       * @param word the word to translate
28       * @return the translated word
29       */
30      @Override
31      public String apply(@Word String word) {
32          return RULES.matcher(word).replaceFirst(TEMPLATE);
33      }
34  }