UNPKG

es-grid-template

Version:

es-grid-template

35 lines (32 loc) 1.17 kB
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */ import * as React from 'react'; // import type { AnyObject } from '../../_util/type'; // import type { GetRowKey, Key } from '../interface'; const useLazyKVMap = (data, childrenColumnName, getRowKey) => { const mapCacheRef = React.useRef({}); function getRecordByKey(key) { if (!mapCacheRef.current || mapCacheRef.current.data !== data || mapCacheRef.current.childrenColumnName !== childrenColumnName || mapCacheRef.current.getRowKey !== getRowKey) { const kvMap = new Map(); // @ts-ignore function dig(records) { records.forEach((record, index) => { const rowKey = getRowKey(record, index); kvMap.set(rowKey, record); if (record && typeof record === 'object' && childrenColumnName in record) { dig(record[childrenColumnName] || []); } }); } dig(data); mapCacheRef.current = { data, childrenColumnName, kvMap, getRowKey }; } return mapCacheRef.current.kvMap?.get(key); } return [getRecordByKey]; }; export default useLazyKVMap;