forked from SpareBank1/designsystem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetListToRender.ts
66 lines (60 loc) · 2.06 KB
/
getListToRender.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { SearchMatcher } from './types';
const toLowerCase = (value: string) => `${value}`.toLowerCase();
const filterDropdownList = <Item extends Record<string, any>>(
dropdownList: Item[],
searchAttributes: Array<keyof Item>,
inputValue: string,
searchMatcher?: SearchMatcher<Item>,
) => {
const filter = searchMatcher
? searchMatcher(inputValue, searchAttributes)
: (item: Item) =>
searchAttributes
.map(searchAttribute => toLowerCase(item[searchAttribute]))
.some(cleanItemAttribute =>
cleanItemAttribute.includes(toLowerCase(inputValue)),
);
return dropdownList.filter(filter);
};
export const getListToRender = <Item extends Record<string, any>>({
inputValue,
searchAttributes,
maxRenderedDropdownElements,
dropdownList,
noMatchDropdownList,
searchMatcher,
showAllItemsInDropdown,
}: {
inputValue: string;
searchAttributes: Array<keyof Item>;
maxRenderedDropdownElements: number;
dropdownList: Item[];
noMatchDropdownList: Item[] | undefined;
searchMatcher?: SearchMatcher<Item>;
showAllItemsInDropdown: boolean;
}): { noMatch: boolean; listToRender: Item[] } => {
const trimmedInput = inputValue ? String(inputValue).trim() : '';
const shouldFilter = trimmedInput.length > 0;
const dropdownListFiltered = shouldFilter
? filterDropdownList(
dropdownList,
searchAttributes,
trimmedInput,
searchMatcher,
).slice(0, maxRenderedDropdownElements)
: dropdownList?.slice(0, maxRenderedDropdownElements);
const listToRender = () => {
if (showAllItemsInDropdown) {
return dropdownList;
} else if (dropdownListFiltered?.length) {
return dropdownListFiltered;
} else if (noMatchDropdownList) {
return noMatchDropdownList;
}
return [];
};
return {
listToRender: listToRender(),
noMatch: !dropdownListFiltered?.length,
};
};