Skip to content

Commit 4c81cdb

Browse files
committed
add map to ARRAY carpenter
1 parent d3d51ee commit 4c81cdb

2 files changed

Lines changed: 56 additions & 1 deletion

File tree

builder/ARRAY.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { STR, STRING } from "../mod.ts";
22
import { WritableBuilder } from "../types/Builder.ts";
33
import { LOGICAL } from "../types/Logical.ts";
44
import LogicalStack from "../types/LogicalStack.ts";
5+
type predicate<K> = ((val: K, index?: number, arr?:K[])=>boolean);
6+
type callBck<K> = ((val: K, index?: number, arr?:K[])=>K | any);
57

68
export class ARR<I> extends LogicalStack<ARR<I>>
79
implements WritableBuilder<Array<I>, ARR<I>>, ArrayLike<I> {
@@ -55,11 +57,30 @@ export class ARR<I> extends LogicalStack<ARR<I>>
5557
* @param predicate
5658
* @returns
5759
*/
58-
public thenFilter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this {
60+
public thenFilter(predicate: predicate<I>): this {
5961
if(this.lastStackMatched) this.filter(predicate);
6062
return this;
6163
}
6264

65+
/**
66+
* Performs Map on the inner value regardless of conditions of previous calls.
67+
* @param predicate
68+
* @returns
69+
*/
70+
public map(predicate: callBck<I>): this {
71+
this.value = this.value.map(predicate);
72+
return this;
73+
}
74+
/**
75+
* Performs map only if the previous calls result in a true value.
76+
* @param predicate
77+
* @returns
78+
*/
79+
public thenMap(predicate: callBck<I>): this {
80+
if(this.lastStackMatched) this.map(predicate);
81+
return this;
82+
}
83+
6384
/**
6485
* Checks if the current array length is of size 'n'
6586
* @param n

tests/ARRAY_test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,3 +174,37 @@ Deno.test("Test array getSection", () => {
174174
});
175175
if (!called) fail("clause was never called");
176176
});
177+
178+
Deno.test("Test array map", () => {
179+
let called = false;
180+
ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).map((x, i, a)=>{
181+
return x * 10;
182+
}).do((arr)=>{
183+
assertEquals(arr[0], 10);
184+
called = true;
185+
})
186+
if (!called) fail("clause was never called");
187+
});
188+
189+
Deno.test("Test array thenMap true", () => {
190+
let called = false;
191+
ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).thenMap((x, i, a)=>{
192+
return x * 10;
193+
}).do((arr)=>{
194+
assertEquals(arr[0], 10);
195+
called = true;
196+
})
197+
if (!called) fail("clause was never called");
198+
});
199+
Deno.test("Test array thenMap false", () => {
200+
let called = false;
201+
ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
202+
.isOfSize(1)
203+
.thenMap((x)=>{
204+
return x * 10;
205+
}).else((arr)=>{
206+
assertEquals(arr[0], 1);
207+
called = true;
208+
})
209+
if (!called) fail("clause was never called");
210+
});

0 commit comments

Comments
 (0)