File tree Expand file tree Collapse file tree 3 files changed +58
-0
lines changed
main/java/com/annimon/ownlang/modules/std
test/resources/modules/std Expand file tree Collapse file tree 3 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -26,6 +26,7 @@ public void init() {
2626 Functions .set ("thread" , new std_thread ());
2727 Functions .set ("sync" , new std_sync ());
2828 Functions .set ("try" , new std_try ());
29+ Functions .set ("default" , new std_default ());
2930
3031 // Numbers
3132 Functions .set ("toHexString" , NumberFunctions ::toHexString );
Original file line number Diff line number Diff line change 1+ package com .annimon .ownlang .modules .std ;
2+
3+ import com .annimon .ownlang .lib .Arguments ;
4+ import com .annimon .ownlang .lib .ArrayValue ;
5+ import com .annimon .ownlang .lib .Function ;
6+ import com .annimon .ownlang .lib .MapValue ;
7+ import com .annimon .ownlang .lib .Types ;
8+ import com .annimon .ownlang .lib .Value ;
9+
10+ public final class std_default implements Function {
11+
12+ @ Override
13+ public Value execute (Value ... args ) {
14+ Arguments .check (2 , args .length );
15+ if (isEmpty (args [0 ])) {
16+ return args [1 ];
17+ }
18+ return args [0 ];
19+ }
20+
21+ private boolean isEmpty (Value value ) {
22+ if (value == null || value .raw () == null ) {
23+ return true ;
24+ }
25+ switch (value .type ()) {
26+ case Types .NUMBER :
27+ return (value .asInt () == 0 );
28+ case Types .STRING :
29+ return (value .asString ().isEmpty ());
30+ case Types .ARRAY :
31+ return ((ArrayValue ) value ).size () == 0 ;
32+ case Types .MAP :
33+ return ((MapValue ) value ).size () == 0 ;
34+ default :
35+ return false ;
36+ }
37+ }
38+ }
Original file line number Diff line number Diff line change 1+ use "std"
2+
3+ def testDefaultNumber() {
4+ assertEquals(123, default(0, 123))
5+ }
6+
7+ def testDefaultString() {
8+ assertEquals("123", default("", "123"))
9+ }
10+
11+ def testDefaultNull() {
12+ use "java"
13+ assertEquals("not null", default(null, "not null"))
14+ }
15+
16+ def testOperatorOverloading() {
17+ def `?:`(a, b) = default(a, b)
18+ assertEquals("not null", "" ?: "not null")
19+ }
You can’t perform that action at this time.
0 commit comments