Factored lookup code from BlockType and ItemType into a method in StringUtil.

This commit is contained in:
TomyLobo 2012-01-30 17:41:18 +01:00
parent d2c64e9304
commit aaac36b1cc
3 changed files with 38 additions and 66 deletions

View File

@ -19,6 +19,7 @@
package com.sk89q.util;
import java.util.Collection;
import java.util.Map;
/**
* String utilities.
@ -270,4 +271,39 @@ public class StringUtil {
// actually has the most recent cost counts
return p[n];
}
public static <T extends Enum<?>> T lookup(Map<String, T> lookup, String name, boolean fuzzy) {
String testName = name.replace("[ _]", "").toLowerCase();
T type = lookup.get(testName);
if (type != null) {
return type;
}
if (!fuzzy) {
return null;
}
int minDist = Integer.MAX_VALUE;
for (Map.Entry<String, T> entry : lookup.entrySet()) {
final String key = entry.getKey();
if (key.charAt(0) != testName.charAt(0)) {
continue;
}
int dist = getLevenshteinDistance(key, testName);
if (dist >= minDist) {
minDist = dist;
type = entry.getValue();
}
}
if (minDist > 1) {
return null;
}
return type;
}
}

View File

@ -23,7 +23,6 @@ import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumSet;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
@ -235,38 +234,7 @@ public enum BlockType {
* @return
*/
public static BlockType lookup(String name, boolean fuzzy) {
String testName = name.replace(" ", "").toLowerCase();
if (testName.length() == 0) {
return null;
}
BlockType type = lookup.get(testName);
if (type != null) {
return type;
}
if (!fuzzy) {
return null;
}
int minDist = -1;
for (Entry<String, BlockType> entry : lookup.entrySet()) {
if (entry.getKey().charAt(0) != testName.charAt(0)) {
continue;
}
int dist = StringUtil.getLevenshteinDistance(entry.getKey(), testName);
if ((dist < minDist || minDist == -1) && dist < 2) {
minDist = dist;
type = entry.getValue();
}
}
return type;
return StringUtil.lookup(lookup, name, fuzzy);
}
/**

View File

@ -24,7 +24,6 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumSet;
import java.util.Map.Entry;
import java.util.Set;
import com.sk89q.util.StringUtil;
@ -413,38 +412,7 @@ public enum ItemType {
* @return
*/
public static ItemType lookup(String name, boolean fuzzy) {
String testName = name.replace(" ", "").toLowerCase();
if (testName.length() == 0) {
return null;
}
ItemType type = lookup.get(testName);
if (type != null) {
return type;
}
if (!fuzzy) {
return null;
}
int minDist = -1;
for (Entry<String, ItemType> entry : lookup.entrySet()) {
if (entry.getKey().charAt(0) != testName.charAt(0)) {
continue;
}
int dist = StringUtil.getLevenshteinDistance(entry.getKey(), testName);
if ((dist < minDist || minDist == -1) && dist < 2) {
minDist = dist;
type = entry.getValue();
}
}
return type;
return StringUtil.lookup(lookup, name, fuzzy);
}
/**