Skip to content

Commit 0e2b92b

Browse files
committed
Поддержка функций-расширений для строк
1 parent 0bbbecc commit 0e2b92b

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/main/java/com/annimon/ownlang/lib/StringValue.java

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,30 @@ public StringValue(String value) {
1717
this.value = value;
1818
}
1919

20-
public Value access(Value property) {
21-
switch (property.asString()) {
20+
public Value access(Value propertyValue) {
21+
final String prop = propertyValue.asString();
22+
switch (prop) {
2223
// Properties
2324
case "length":
2425
return NumberValue.of(length());
2526

2627
// Functions
2728
case "trim":
2829
return new FunctionValue(args -> new StringValue(value.trim()));
30+
31+
default:
32+
if (Functions.isExists(prop)) {
33+
final Function f = Functions.get(prop);
34+
return new FunctionValue(args -> {
35+
final Value[] newArgs = new Value[args.length + 1];
36+
newArgs[0] = this;
37+
System.arraycopy(args, 0, newArgs, 1, args.length);
38+
return f.execute(newArgs);
39+
});
40+
}
41+
break;
2942
}
30-
throw new UnknownPropertyException(property.asString());
43+
throw new UnknownPropertyException(prop);
3144
}
3245

3346
public int length() {

src/test/resources/other/stringFunctions.own

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,15 @@ def testLength() {
77
def testTrim() {
88
s = " test "
99
assertEquals("test", s.trim())
10+
}
11+
12+
def testExtensionFunction() {
13+
use "std"
14+
s = "1es1"
15+
assertEquals("test", s.replace("1", "t"))
16+
}
17+
18+
def testExtensionCustomFunction() {
19+
def repeat(str, num) = str * num
20+
assertEquals("****", "*".repeat(4))
1021
}

0 commit comments

Comments
 (0)