diff --git a/builder/ARRAY.ts b/builder/ARRAY.ts index e3ac63e..da3daa4 100644 --- a/builder/ARRAY.ts +++ b/builder/ARRAY.ts @@ -41,6 +41,25 @@ export class ARR extends LogicalStack> return this; } + /** + * Performs a filter on the inner value regardless if stack is true or false. + * @param predicate + * @returns + */ + public filter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this { + this.value = this.value.filter(predicate); + return this; + } + /** + * Performs a filter if the previous chain items result in a "true". + * @param predicate + * @returns + */ + public thenFilter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this { + if(this.lastStackMatched) this.filter(predicate); + return this; + } + /** * Checks if the current array length is of size 'n' * @param n diff --git a/tests/ARRAY_test.ts b/tests/ARRAY_test.ts index e7c29f5..7543dfc 100644 --- a/tests/ARRAY_test.ts +++ b/tests/ARRAY_test.ts @@ -8,6 +8,30 @@ import { } from "https://deno.land/std@0.90.0/testing/asserts.ts"; import { ARRAY } from "../mod.ts"; + +Deno.test("Test array filter", () => { + let called = false; + ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).filter((x)=>x == 1).do((arr)=>{ + assertEquals(arr[0], 1); + called = true; + }) + if (!called) fail("clause was never called"); +}); +Deno.test("Test array thenFilter", () => { + let called = false; + ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + .isOfSize(0) + .thenFilter((x)=>{fail("incorrect clause"); return false}) + .or() + .isOfSize(10) + .thenFilter((x)=>x == 1).do((arr)=>{ + assertEquals(arr[0], 1); + assertEquals(arr.length, 1); + called = true; + }) + if (!called) fail("clause was never called"); +}); + Deno.test("Test array append()", () => { let called = false; ARRAY(["hello"]).append("world").do((cv) => {