优化:字典缓存使用Map代替Array,更高效

This commit is contained in:
月夜 2024-11-11 15:10:24 +08:00
parent 4310e5e049
commit 9836d6d9bd

View File

@ -1,29 +1,15 @@
export const useDictStore = defineStore('dict', () => { export const useDictStore = defineStore('dict', () => {
const dict = ref< const dict = ref<Map<string, DictDataOption[]>>(new Map());
Array<{
key: string;
value: DictDataOption[];
}>
>([]);
/** /**
* *
* @param _key key * @param _key key
*/ */
const getDict = (_key: string): DictDataOption[] | null => { const getDict = (_key: string): DictDataOption[] | null => {
if (_key == null && _key == '') { if (!_key) {
return null; return null;
} }
try { return dict.value.get(_key) || null;
for (let i = 0; i < dict.value.length; i++) {
if (dict.value[i].key == _key) {
return dict.value[i].value;
}
}
} catch (e) {
return null;
}
return null;
}; };
/** /**
@ -32,11 +18,15 @@ export const useDictStore = defineStore('dict', () => {
* @param _value value * @param _value value
*/ */
const setDict = (_key: string, _value: DictDataOption[]) => { const setDict = (_key: string, _value: DictDataOption[]) => {
if (_key !== null && _key !== '') { if (!_key) {
dict.value.push({ return false;
key: _key, }
value: _value try {
}); dict.value.set(_key, _value);
return true;
} catch (e) {
console.error('Error in setDict:', e);
return false;
} }
}; };
@ -45,25 +35,22 @@ export const useDictStore = defineStore('dict', () => {
* @param _key * @param _key
*/ */
const removeDict = (_key: string): boolean => { const removeDict = (_key: string): boolean => {
let bln = false; if (!_key) {
try { return false;
for (let i = 0; i < dict.value.length; i++) { }
if (dict.value[i].key == _key) { try {
dict.value.splice(i, 1); return dict.value.delete(_key);
return true; } catch (e) {
} console.error('Error in removeDict:', e);
} return false;
} catch (e) {
bln = false;
} }
return bln;
}; };
/** /**
* *
*/ */
const cleanDict = (): void => { const cleanDict = (): void => {
dict.value = []; dict.value.clear();
}; };
return { return {