Sfoglia il codice sorgente

Extending StringFormatter's if-then-else clause to support integer comparison as a built-in operation.

Sam Jaffe 8 anni fa
parent
commit
c4ea843366

+ 22 - 1
src/org/leumasjaffe/format/StringFormatter.java

@@ -2,6 +2,8 @@ package org.leumasjaffe.format;
 
 import java.util.HashMap;
 import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import lombok.AccessLevel;
 import lombok.experimental.FieldDefaults;
@@ -83,7 +85,7 @@ public class StringFormatter {
 			// If token starts with '%', make it a c-format expression
 			if (token.indexOf('?') != -1) {
 				final int b1 = fmt.indexOf('?', pos)+1;
-				boolean _if = (Boolean) getToken(token.substring(0, b1-pos-1));
+				boolean _if = getConditionToken(token, b1-pos-1);
 				FmtStateMachine then = new FmtStateMachine(fmt.substring(b1), currentIdx, args, named, ':').formatMain();
 				FmtStateMachine els = new FmtStateMachine(fmt.substring(then.endPos+b1), then.currentIdx, args, named, '}').formatMain();
 				currentIdx = els.currentIdx;
@@ -95,6 +97,25 @@ public class StringFormatter {
 			return epos;
 		}
 
+		private boolean getConditionToken(final String token, final int end) {
+			final String cond = token.substring(0, end);
+			Matcher matcher = Pattern.compile("^(\\d*|[a-zA-Z_]+)(>=?|<=?|!=|==)(\\d+)$").matcher(cond);
+			if (matcher.matches()) {
+				final int cmp = ((Integer) getToken(matcher.group(1))).compareTo(Integer.valueOf(matcher.group(3)));
+				switch (matcher.group(2)) {
+				case "==": return cmp == 0;
+				case "!=": return cmp != 0;
+				case "<" : return cmp <  0;
+				case "<=": return cmp <= 0;
+				case ">" : return cmp >  0;
+				case ">=": return cmp >= 0;
+				default: throw new IllegalStateException();
+				}
+			} else {
+				return (Boolean) getToken(cond);
+			}
+		}
+
 		private Object getToken(final String token) {
 			if (token == null || token.isEmpty()) {
 				return args[currentIdx++];

+ 5 - 0
test/org/leumasjaffe/format/StringFormatterTest.java

@@ -26,5 +26,10 @@ public class StringFormatterTest {
 	public void testFormatNumberedCondition() {
 		assertEquals("0 word + 1 word/2 levels", StringHelper.format("{0} {2} + {1} {2}/{3?level:{4} levels}", 0, 1, "word", false, 2));
 	}
+	
+	@Test
+	public void testFormatIntegerCompareCondition() {
+		assertEquals("true", StringHelper.format("{>1?true:false}", 2));
+	}
 
 }