From 089be8395355f2437b7ba74c2560cb0ff4248309 Mon Sep 17 00:00:00 2001 From: Craig Perkins Date: Wed, 1 Nov 2023 21:36:14 -0400 Subject: [PATCH] Add tests Signed-off-by: Craig Perkins --- .../src/main/java/org/opensearch/common/regex/Regex.java | 8 +++----- .../test/java/org/opensearch/common/regex/RegexTests.java | 8 ++++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/server/src/main/java/org/opensearch/common/regex/Regex.java b/server/src/main/java/org/opensearch/common/regex/Regex.java index fffe5f6a70057..315b86a9b329f 100644 --- a/server/src/main/java/org/opensearch/common/regex/Regex.java +++ b/server/src/main/java/org/opensearch/common/regex/Regex.java @@ -97,15 +97,13 @@ public static Automaton simpleMatchToAutomaton(String... patterns) { * * @param str - The input string to remove adjacent duplicate characters from * @param target - The target character to remove duplicates of - * @return + * @return - string with adjacent duplicates of the target character removed */ - public static String removeDuplicates(String str, char target) { + static String removeDuplicates(String str, char target) { StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { int size = sb.length(); - if (size > 0 && c == target && sb.charAt(size - 1) == c) { - sb.deleteCharAt(size - 1); - } else { + if (size == 0 || c != target || sb.charAt(size - 1) != c) { sb.append(c); } } diff --git a/server/src/test/java/org/opensearch/common/regex/RegexTests.java b/server/src/test/java/org/opensearch/common/regex/RegexTests.java index b92fcdad56d74..93304e1c2525b 100644 --- a/server/src/test/java/org/opensearch/common/regex/RegexTests.java +++ b/server/src/test/java/org/opensearch/common/regex/RegexTests.java @@ -122,4 +122,12 @@ public void testSimpleMatch() { assertFalse("[" + pattern + "] should not match [" + matchingString + "]", Regex.simpleMatch(pattern, matchingString)); } } + + public void testRemoveDuplicates() { + assertEquals("*", Regex.removeDuplicates("***", '*')); + assertEquals("*abc*", Regex.removeDuplicates("**abc**", '*')); + assertEquals("a*b*c*", Regex.removeDuplicates("a*b**c****", '*')); + assertEquals("*abc", Regex.removeDuplicates("****abc", '*')); + assertEquals("*", Regex.removeDuplicates("*".repeat(100), '*')); + } }