import type { Ref } from 'vue'; import { watch, shallowRef } from 'vue'; import type { Key, GetRowKey } from '../interface'; interface MapCache { kvMap?: Map; } export default function useLazyKVMap( dataRef: Ref, childrenColumnNameRef: Ref, getRowKeyRef: Ref>, ) { const mapCacheRef = shallowRef>({}); watch( [dataRef, childrenColumnNameRef, getRowKeyRef], () => { const kvMap = new Map(); const getRowKey = getRowKeyRef.value; const childrenColumnName = childrenColumnNameRef.value; /* eslint-disable no-inner-declarations */ function dig(records: readonly RecordType[]) { records.forEach((record, index) => { const rowKey = getRowKey(record, index); kvMap.set(rowKey, record); if (record && typeof record === 'object' && childrenColumnName in record) { dig((record as any)[childrenColumnName] || []); } }); } /* eslint-enable */ dig(dataRef.value); mapCacheRef.value = { kvMap, }; }, { deep: true, immediate: true, }, ); function getRecordByKey(key: Key): RecordType { return mapCacheRef.value.kvMap!.get(key)!; } return [getRecordByKey]; }