diff --git a/builder/ARRAY.ts b/builder/ARRAY.ts index da3daa4..033d459 100644 --- a/builder/ARRAY.ts +++ b/builder/ARRAY.ts @@ -2,6 +2,8 @@ import { STR, STRING } from "../mod.ts"; import { WritableBuilder } from "../types/Builder.ts"; import { LOGICAL } from "../types/Logical.ts"; import LogicalStack from "../types/LogicalStack.ts"; +type predicate = ((val: K, index?: number, arr?:K[])=>boolean); +type callBck = ((val: K, index?: number, arr?:K[])=>K | any); export class ARR extends LogicalStack> implements WritableBuilder, ARR>, ArrayLike { @@ -55,11 +57,30 @@ export class ARR extends LogicalStack> * @param predicate * @returns */ - public thenFilter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this { + public thenFilter(predicate: predicate): this { if(this.lastStackMatched) this.filter(predicate); return this; } + /** + * Performs Map on the inner value regardless of conditions of previous calls. + * @param predicate + * @returns + */ + public map(predicate: callBck): this { + this.value = this.value.map(predicate); + return this; + } + /** + * Performs map only if the previous calls result in a true value. + * @param predicate + * @returns + */ + public thenMap(predicate: callBck): this { + if(this.lastStackMatched) this.map(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 7543dfc..e93b56f 100644 --- a/tests/ARRAY_test.ts +++ b/tests/ARRAY_test.ts @@ -174,3 +174,37 @@ Deno.test("Test array getSection", () => { }); if (!called) fail("clause was never called"); }); + +Deno.test("Test array map", () => { + let called = false; + ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).map((x, i, a)=>{ + return x * 10; + }).do((arr)=>{ + assertEquals(arr[0], 10); + called = true; + }) + if (!called) fail("clause was never called"); +}); + +Deno.test("Test array thenMap true", () => { + let called = false; + ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).thenMap((x, i, a)=>{ + return x * 10; + }).do((arr)=>{ + assertEquals(arr[0], 10); + called = true; + }) + if (!called) fail("clause was never called"); +}); +Deno.test("Test array thenMap false", () => { + let called = false; + ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + .isOfSize(1) + .thenMap((x)=>{ + return x * 10; + }).else((arr)=>{ + assertEquals(arr[0], 1); + called = true; + }) + if (!called) fail("clause was never called"); +}); \ No newline at end of file