1 | import { useMemo } from 'react';
|
2 | export const dataValue = (dataItem, field) => {
|
3 | if (typeof field === 'function') return field(dataItem);
|
4 | if (dataItem == null) return dataItem;
|
5 | if (typeof field === 'string' && typeof dataItem === 'object' && field in dataItem) return dataItem[field];
|
6 | return dataItem;
|
7 | };
|
8 | export const dataText = (dataItem, textField) => {
|
9 | const value = dataValue(dataItem, textField);
|
10 | return value == null ? '' : String(value);
|
11 | };
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export function valueMatcher(a, b, dataKey) {
|
18 | return dataValue(a, dataKey) === dataValue(b, dataKey);
|
19 | }
|
20 | export function dataIndexOf(data, value, dataKey) {
|
21 | const valueDataKey = dataValue(value, dataKey);
|
22 | let idx = -1;
|
23 |
|
24 | while (++idx < data.length) {
|
25 | const datum = data[idx];
|
26 | if (datum === value || dataValue(datum, dataKey) === valueDataKey) return idx;
|
27 | }
|
28 |
|
29 | return -1;
|
30 | }
|
31 | export function dataItem(data, value, dataKey) {
|
32 | const idx = dataIndexOf(data, value, dataKey);
|
33 |
|
34 | return idx !== -1 ? data[idx] : value;
|
35 | }
|
36 | export const useAccessors = (textField, dataKey) => {
|
37 | return useMemo(() => ({
|
38 | text: item => dataText(item, textField),
|
39 | value: item => dataValue(item, dataKey),
|
40 | indexOf: (data, value) => dataIndexOf(data, value, dataKey),
|
41 | matches: (a, b) => valueMatcher(a, b, dataKey),
|
42 | findOrSelf: (data, value) => dataItem(data, value, dataKey),
|
43 | includes: (data, value) => dataIndexOf(data, value, dataKey) !== -1
|
44 | }), [textField, dataKey]);
|
45 | }; |
\ | No newline at end of file |