MapHelpers.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  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. * @template K
  11. * @template V
  12. * @param {Map<K, V>} map The map object to check
  13. * @param {K} key The key to check
  14. * @param {function(): V} computer function which will compute the value if it doesn't exist
  15. * @returns {V} The value from the map, or the computed value
  16. * @example
  17. * ```js
  18. * const map = new Map();
  19. * const value = getOrInsert(map, "key", () => "value");
  20. * console.log(value); // "value"
  21. * ```
  22. */
  23. module.exports.getOrInsert = (map, key, computer) => {
  24. // Grab key from map
  25. const value = map.get(key);
  26. // If the value already exists, return it
  27. if (value !== undefined) return value;
  28. // Otherwise compute the value, set it in the map, and return it
  29. const newValue = computer();
  30. map.set(key, newValue);
  31. return newValue;
  32. };