Skip to content

Instantly share code, notes, and snippets.

@MichaelScofield
Created June 12, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelScofield/489189c64b47a506f3b05bca3c6ab75b to your computer and use it in GitHub Desktop.
Save MichaelScofield/489189c64b47a506f3b05bca3c6ab75b to your computer and use it in GitHub Desktop.
import org.apache.commons.lang3.tuple.Pair;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
//noinspection unchecked
Pair<String, Boolean>[] testCases = new Pair[]{
Pair.of("ex 1", true),
Pair.of("px 1", true),
Pair.of("ex 1 ex 2", true),
Pair.of("ex 1 px 2", true),
Pair.of("px 1 px 2", true),
Pair.of("px 1 ex 2", true),
Pair.of("ex ex 1", false),
Pair.of("px px 1", false),
Pair.of("ex 1 ex", false),
Pair.of("ex 1 ex 2 ex 3", true),
Pair.of("ex 1 ex 2 px 3", true),
Pair.of("ex 1 px 2 px 3", true),
Pair.of("ex y", false),
Pair.of("px y", false),
Pair.of("nx nx nx", true),
Pair.of("nx xx", false),
Pair.of("xx nx", false),
Pair.of("ex 1 nx nx", true),
Pair.of("xx px 1 xx", true),
Pair.of("ex nx 1", false),
Pair.of("nx px 1", false),
};
for (Pair<String, Boolean> testcase : testCases) {
boolean expected = testcase.getRight();
boolean actual = test(testcase.getLeft().split(" "));
System.out.println(String.format("expect %s, actual %s", expected, actual));
System.out.println();
}
}
private static boolean test(String[] attributes) {
System.out.println(Arrays.toString(attributes));
boolean hasNX = false;
boolean hasXX = false;
long expireMilliseconds = -1;
for (int i = 0, l = attributes.length; i < l; i++) {
String attribute = attributes[i];
switch (attribute.toUpperCase()) {
case "EX":
// EX后面必须带数字
if (i + 1 < l) {
try {
expireMilliseconds = Integer.parseInt(attributes[++i]) * 1000;
} catch (NumberFormatException e) {
return false;
}
} else {
return false;
}
break;
case "PX":
// PX后面必须带数字
if (i + 1 < l) {
try {
expireMilliseconds = Long.parseLong(attributes[++i]);
} catch (NumberFormatException e) {
return false;
}
} else {
return false;
}
break;
case "NX":
hasNX = true;
break;
case "XX":
hasXX = true;
break;
default:
return false;
}
}
if (hasNX && hasXX) {
return false;
}
System.out.println(String.format(
"expireMilliseconds = %s, NX = %s, XX = %s", expireMilliseconds, hasNX, hasXX));
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment