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

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;
}
public Value access(Value property) {
switch (property.asString()) {
public Value access(Value propertyValue) {
final String prop = propertyValue.asString();
switch (prop) {
// Properties
case "length":
return NumberValue.of(length());
@ -26,8 +27,20 @@ public final class StringValue implements Value {
// Functions
case "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);
});
}
throw new UnknownPropertyException(property.asString());
break;
}
throw new UnknownPropertyException(prop);
}
public int length() {

View File

@ -8,3 +8,14 @@ def testTrim() {
s = " test "
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))
}