Created
July 23, 2024 12:54
-
-
Save spaceemotion/2a06b672b76c42275ddbae44271dcf81 to your computer and use it in GitHub Desktop.
A couple "intelligent" references (set and map) for VueJS 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { customRef } from "vue"; | |
export const isDifferentSet = <T>(newSet: Set<T>, oldSet: Set<T>): boolean => { | |
if (newSet.size !== oldSet.size) { | |
return true; | |
} | |
for (const value of newSet) { | |
if (!oldSet.has(value)) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
export const isDifferentMap = <K, V>(newMap: Map<K, V>, oldMap: Map<K, V>): boolean => { | |
if (newMap.size !== oldMap.size) { | |
return true; | |
} | |
for (const [key, value] of newMap) { | |
if (oldMap.get(key) !== value) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
export const useIntelligentSetRef = <T>(initial: Set<T>) => { | |
return customRef((track, trigger) => { | |
let set = initial; | |
return { | |
get() { | |
track(); | |
return set; | |
}, | |
set(newSet: Set<T>) { | |
if (isDifferentSet(newSet, set)) { | |
set = newSet; | |
trigger(); | |
} | |
}, | |
}; | |
}); | |
}; | |
export const useIntelligentMapRef = <K, V>(initial: Map<K, V>) => { | |
return customRef((track, trigger) => { | |
let map = initial; | |
return { | |
get() { | |
track(); | |
return map; | |
}, | |
set(newMap: Map<K, V>) { | |
if (isDifferentMap(newMap, map)) { | |
map = newMap; | |
trigger(); | |
} | |
}, | |
}; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment