mirror of
https://github.com/aNNiMON/Own-Programming-Language-Tutorial.git
synced 2024-09-20 00:34:20 +03:00
Поддержка функций-расширений для строк
This commit is contained in:
parent
0bbbeccda6
commit
0e2b92bfac
@ -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() {
|
||||||
|
@ -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))
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user