-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
52 lines (46 loc) · 1.45 KB
/
index.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { DEFAULT_THRESHOLD as THRESHOLD } from "./constants.js";
type FilterFunction<Element> = (element: Element, index: number, array: Element[]) => boolean;
type MapFunction<Element, Output> = (element: Element, index: number, array: Element[]) => Output;
const filterMap_LONG = <Element, Output>(
array: Element[],
filter: FilterFunction<Element>,
map: MapFunction<Element, Output>,
): Output[] => {
const arrayLength = array.length;
const result = new Array<Output>(arrayLength);
let index = 0;
let outputI = 0;
while (index < arrayLength) {
const element = array[index];
if (filter(element, index, array)) {
result[outputI] = map(element, index, array);
outputI++;
}
index++;
}
result.length = outputI;
return result;
};
const filterMap_SHORT = <Element, Output>(
array: Element[],
filter: FilterFunction<Element>,
map: MapFunction<Element, Output>
): Output[] => {
const arrayLength = array.length;
const result = new Array(0);
let index = 0;
while (index < arrayLength) {
const element = array[index];
if (filter(element, index, array)) {
result.push(map(element, index, array));
}
index++;
}
return result;
};
const filterMap = <Element, Output>(
array: Element[],
filter: FilterFunction<Element>,
map: MapFunction<Element, Output>
): Output[] => array.length > THRESHOLD ? filterMap_LONG(array, filter, map) : filterMap_SHORT(array, filter, map);
export default filterMap;