Skip to content

Commit d3d51ee

Browse files
committed
add ARRAY filter methods
1 parent 3b95038 commit d3d51ee

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

builder/ARRAY.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,25 @@ export class ARR<I> extends LogicalStack<ARR<I>>
4141
return this;
4242
}
4343

44+
/**
45+
* Performs a filter on the inner value regardless if stack is true or false.
46+
* @param predicate
47+
* @returns
48+
*/
49+
public filter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this {
50+
this.value = this.value.filter(predicate);
51+
return this;
52+
}
53+
/**
54+
* Performs a filter if the previous chain items result in a "true".
55+
* @param predicate
56+
* @returns
57+
*/
58+
public thenFilter(predicate: (val: I, index?: number, arr?:I[])=>boolean): this {
59+
if(this.lastStackMatched) this.filter(predicate);
60+
return this;
61+
}
62+
4463
/**
4564
* Checks if the current array length is of size 'n'
4665
* @param n

tests/ARRAY_test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,30 @@ import {
88
} from "https://deno.land/std@0.90.0/testing/asserts.ts";
99
import { ARRAY } from "../mod.ts";
1010

11+
12+
Deno.test("Test array filter", () => {
13+
let called = false;
14+
ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).filter((x)=>x == 1).do((arr)=>{
15+
assertEquals(arr[0], 1);
16+
called = true;
17+
})
18+
if (!called) fail("clause was never called");
19+
});
20+
Deno.test("Test array thenFilter", () => {
21+
let called = false;
22+
ARRAY([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
23+
.isOfSize(0)
24+
.thenFilter((x)=>{fail("incorrect clause"); return false})
25+
.or()
26+
.isOfSize(10)
27+
.thenFilter((x)=>x == 1).do((arr)=>{
28+
assertEquals(arr[0], 1);
29+
assertEquals(arr.length, 1);
30+
called = true;
31+
})
32+
if (!called) fail("clause was never called");
33+
});
34+
1135
Deno.test("Test array append()", () => {
1236
let called = false;
1337
ARRAY(["hello"]).append("world").do((cv) => {

0 commit comments

Comments
 (0)