Поддержка функций-расширений для строк

This commit is contained in:
Victor 2019-01-04 22:23:28 +02:00
parent 0bbbeccda6
commit 0e2b92bfac
2 changed files with 27 additions and 3 deletions

View File

@ -17,8 +17,9 @@ public final class StringValue implements Value {
this.value = value; this.value = value;
} }
public Value access(Value property) { public Value access(Value propertyValue) {
switch (property.asString()) { final String prop = propertyValue.asString();
switch (prop) {
// Properties // Properties
case "length": case "length":
return NumberValue.of(length()); return NumberValue.of(length());
@ -26,8 +27,20 @@ public final class StringValue implements Value {
// Functions // Functions
case "trim": case "trim":
return new FunctionValue(args -> new StringValue(value.trim())); return new FunctionValue(args -> new StringValue(value.trim()));
default:
if (Functions.isExists(prop)) {
final Function f = Functions.get(prop);
return new FunctionValue(args -> {
final Value[] newArgs = new Value[args.length + 1];
newArgs[0] = this;
System.arraycopy(args, 0, newArgs, 1, args.length);
return f.execute(newArgs);
});
}
break;
} }
throw new UnknownPropertyException(property.asString()); throw new UnknownPropertyException(prop);
} }
public int length() { public int length() {

View File

@ -7,4 +7,15 @@ def testLength() {
def testTrim() { def testTrim() {
s = " test " s = " test "
assertEquals("test", s.trim()) assertEquals("test", s.trim())
}
def testExtensionFunction() {
use "std"
s = "1es1"
assertEquals("test", s.replace("1", "t"))
}
def testExtensionCustomFunction() {
def repeat(str, num) = str * num
assertEquals("****", "*".repeat(4))
} }