-
Notifications
You must be signed in to change notification settings - Fork 5
/
select-input.transformers.ts
98 lines (98 loc) · 2.94 KB
/
select-input.transformers.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
export function keyToSelectInput(
options: {
idField?: string;
titleField?: string;
items?: { id: string | number, title: string }[],
isArray?: boolean;
}
) {
return (
key:
string |
number |
(string | number)[]
) => {
if (options.isArray === undefined) {
options.isArray = false;
}
if (options.idField === undefined) {
options.idField = 'id';
}
const itemsIsEmpty = !options.items || options.items.length === 0;
if (itemsIsEmpty) {
options.items = [];
}
const keys = (
options.isArray ? key : (key !== undefined ? [key] : [])
) as (string | number)[];
keys.forEach(eachKey => {
if (itemsIsEmpty) {
options.items.push({
id: eachKey,
title: eachKey as string,
});
}
});
const transformedItems = options.items.map(
item => ({
id: item[options.idField],
title: options.titleField ? item[options.titleField] : (item || item['title'] || ''),
})
);
const items = keys.map(
eachKey =>
transformedItems.filter(item =>
item.id === eachKey
)[0]
);
return options.isArray ? items : items[0];
};
}
export function selectInputToKey(
options: {
idField?: string;
titleField?: string;
items?: { id: string | number, title: string }[],
isArray?: boolean;
}
) {
return (
object:
{ id: string | number, title: string } |
{ id: string | number, title: string }[]
) => {
if (options.isArray === undefined) {
options.isArray = false;
}
if (options.idField === undefined) {
options.idField = 'id';
}
const itemsIsEmpty = !options.items || options.items.length === 0;
if (itemsIsEmpty) {
options.items = [];
}
const objects = (
options.isArray ? object : (object ? [object] : [])
) as { id: string | number, title: string }[];
objects.forEach(eachObject => {
if (itemsIsEmpty) {
options.items.push(eachObject);
}
});
const transformedItems = options.items.map(
item => ({
id: item[options.idField],
title: options.titleField ? item[options.titleField] : (item || item['title'] || '')
})
);
const keys = objects.map(
eachObject => {
const item = transformedItems.filter(eachItem =>
eachItem.id === eachObject.id
)[0];
return item ? item.id : item;
}
);
return options.isArray ? keys : keys[0];
};
}