useCache.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import _extends from "@babel/runtime/helpers/esm/extends";
  2. import { shallowRef, computed } from 'vue';
  3. /**
  4. * Cache `value` related LabeledValue & options.
  5. */
  6. export default ((labeledValues, valueOptions) => {
  7. const cacheRef = shallowRef({
  8. values: new Map(),
  9. options: new Map()
  10. });
  11. const filledLabeledValues = computed(() => {
  12. const {
  13. values: prevValueCache,
  14. options: prevOptionCache
  15. } = cacheRef.value;
  16. // Fill label by cache
  17. const patchedValues = labeledValues.value.map(item => {
  18. var _a;
  19. if (item.label === undefined) {
  20. return _extends(_extends({}, item), {
  21. label: (_a = prevValueCache.get(item.value)) === null || _a === void 0 ? void 0 : _a.label
  22. });
  23. }
  24. return item;
  25. });
  26. // Refresh cache
  27. const valueCache = new Map();
  28. const optionCache = new Map();
  29. patchedValues.forEach(item => {
  30. valueCache.set(item.value, item);
  31. optionCache.set(item.value, valueOptions.value.get(item.value) || prevOptionCache.get(item.value));
  32. });
  33. cacheRef.value.values = valueCache;
  34. cacheRef.value.options = optionCache;
  35. return patchedValues;
  36. });
  37. const getOption = val => valueOptions.value.get(val) || cacheRef.value.options.get(val);
  38. return [filledLabeledValues, getOption];
  39. });