-
Notifications
You must be signed in to change notification settings - Fork 7
/
filter.ts
36 lines (29 loc) · 818 Bytes
/
filter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// * ================================================================================ original
{
const result = [1, 2, 3, 4].filter((e, i, a) => {
const keep = Boolean(e % 2);
console.log(e, i, a, keep);
return keep;
});
console.log(result);
}
console.log('--------');
// * ================================================================================ our
{
const filter = <T>(fn: (e: T, i: number, a: T[]) => Boolean | undefined, arr: T[]): T[] => {
const result: T[] = [];
for (let i = 0; i < arr.length; i++) {
fn(arr[i], i, arr) && result.push(arr[i]);
}
return result;
};
const result = filter(
(e, i, a) => {
const keep = Boolean(e % 2);
console.log(e, i, a, keep);
return keep;
},
[6, 7, 8, 9],
);
console.log(result);
}