diff --git a/builtin/core.wren b/builtin/core.wren index afb3d182..381ab6bb 100644 --- a/builtin/core.wren +++ b/builtin/core.wren @@ -16,7 +16,7 @@ class List { } return result } - + map (f) { var result = [] for (element in this) { @@ -24,4 +24,12 @@ class List { } return result } + + where (f) { + var result = [] + for (element in this) { + if (f.call(element)) result.add(element) + } + return result + } } diff --git a/src/wren_core.c b/src/wren_core.c index 4e0356db..c4fcd5be 100644 --- a/src/wren_core.c +++ b/src/wren_core.c @@ -67,6 +67,14 @@ static const char* libSource = " }\n" " return result\n" " }\n" +" \n" +" where (f) {\n" +" var result = []\n" +" for (element in this) {\n" +" if (f.call(element)) result.add(element)\n" +" }\n" +" return result\n" +" }\n" "}\n"; // Validates that the given argument in [args] is a Num. Returns true if it is. @@ -275,9 +283,9 @@ static PrimitiveResult callFunction(WrenVM* vm, Value* args, int numArgs) { fn = AS_FN(args[0]); } - + if (numArgs < fn->numParams) RETURN_ERROR("Function expects more arguments."); - + return PRIM_CALL; } diff --git a/test/list/where.wren b/test/list/where.wren new file mode 100644 index 00000000..d8b0a2f3 --- /dev/null +++ b/test/list/where.wren @@ -0,0 +1,8 @@ +var a = [1, 2, 3] +var moreThan1 = fn (x) { return x > 1 } +var moreThan10 = fn (x) { return x > 10 } +var b = a.where(moreThan1) +var c = a.where(moreThan10) + +IO.print(b) // expect: [2, 3] +IO.print(c) // expect: []