MapHelpers.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * getOrInsert is a helper function for maps that allows you to get a value
  8. * from a map if it exists, or insert a new value if it doesn't. If it value doesn't
  9. * exist, it will be computed by the provided function.
  10. *
  11. * @template K
  12. * @template V
  13. * @param {Map<K, V>} map The map object to check
  14. * @param {K} key The key to check
  15. * @param {function(): V} computer function which will compute the value if it doesn't exist
  16. * @returns {V} The value from the map, or the computed value
  17. *
  18. * @example
  19. * ```js
  20. * const map = new Map();
  21. * const value = getOrInsert(map, "key", () => "value");
  22. * console.log(value); // "value"
  23. * ```
  24. */
  25. exports.getOrInsert = (map, key, computer) => {
  26. // Grab key from map
  27. const value = map.get(key);
  28. // If the value already exists, return it
  29. if (value !== undefined) return value;
  30. // Otherwise compute the value, set it in the map, and return it
  31. const newValue = computer();
  32. map.set(key, newValue);
  33. return newValue;
  34. };