Skip to content

Commit

Permalink
add map to ARRAY carpenter
Browse files Browse the repository at this point in the history
  • Loading branch information
duart38 committed Mar 17, 2021
1 parent d3d51ee commit 4c81cdb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
23 changes: 22 additions & 1 deletion builder/ARRAY.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<K> = ((val: K, index?: number, arr?:K[])=>boolean);
type callBck<K> = ((val: K, index?: number, arr?:K[])=>K | any);

export class ARR<I> extends LogicalStack<ARR<I>>
implements WritableBuilder<Array<I>, ARR<I>>, ArrayLike<I> {
Expand Down Expand Up @@ -55,11 +57,30 @@ export class ARR<I> extends LogicalStack<ARR<I>>
* @param predicate
* @returns
*/
public thenFilter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this {
public thenFilter(predicate: predicate<I>): 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<I>): 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<I>): this {
if(this.lastStackMatched) this.map(predicate);
return this;
}

/**
* Checks if the current array length is of size 'n'
* @param n
Expand Down
34 changes: 34 additions & 0 deletions tests/ARRAY_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});

0 comments on commit 4c81cdb

Please sign in to comment.