[util] NameUtilCore.uniqName

GitOrigin-RevId: 9ff6d21d5e1efc735239d79a80c8993f476d7a5d
This commit is contained in:
Tagir Valeev
2024-03-15 15:59:47 +01:00
committed by intellij-monorepo-bot
parent eadfa417ab
commit 832b80f75b
2 changed files with 38 additions and 0 deletions

View File

@@ -6,6 +6,7 @@ import com.intellij.util.text.NameUtilCore;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -72,4 +73,14 @@ public class NameUtilTest {
final String[] result = NameUtil.splitNameIntoWords(name); final String[] result = NameUtil.splitNameIntoWords(name);
assertEquals(Arrays.asList(expected).toString(), Arrays.asList(result).toString()); assertEquals(Arrays.asList(expected).toString(), Arrays.asList(result).toString());
} }
@Test
public void testUniqName() {
assertEquals("best", NameUtilCore.uniqName("best", Set.of("test", "test1")::contains));
assertEquals("test1", NameUtilCore.uniqName("test", Set.of("test")::contains));
assertEquals("test2", NameUtilCore.uniqName("test", Set.of("test", "test1")::contains));
assertEquals("test3", NameUtilCore.uniqName("test", Set.of("test", "test1", "test2")::contains));
assertEquals("test3", NameUtilCore.uniqName("test1", Set.of("test", "test1", "test2")::contains));
assertEquals("test3", NameUtilCore.uniqName("test2", Set.of("test", "test1", "test2")::contains));
}
} }

View File

@@ -7,6 +7,8 @@ import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public final class NameUtilCore { public final class NameUtilCore {
@@ -168,4 +170,29 @@ public final class NameUtilCore {
} }
return ArrayUtilRt.toStringArray(array); return ArrayUtilRt.toStringArray(array);
} }
/**
* Generates a unique name
*
* @param origName original symbol name
* @param alreadyUsed a predicate that returns true if a supplied name is already used and we cannot use it
* @return the name based on the origName, which is definitely not used (typically by adding a numeric suffix)
*/
public static @NotNull String uniqName(@NotNull String origName, @NotNull Predicate<@NotNull String> alreadyUsed) {
if (!alreadyUsed.test(origName)) return origName;
String baseName = origName;
int index = 0;
Pattern pattern = Pattern.compile("(.+?)(\\d+)");
java.util.regex.Matcher matcher = pattern.matcher(baseName);
if (matcher.matches()) {
baseName = matcher.group(1);
index = Integer.parseInt(matcher.group(2));
}
while (true) {
String name = baseName + (++index);
if (!alreadyUsed.test(name)) {
return name;
}
}
}
} }