putIfAbsent.js 482 B

12345678910111213141516171819202122
  1. 'use strict';
  2. /**
  3. * If `map` already has the given `key`, returns its value. Otherwise, calls
  4. * `callback`, adds the result to `map` at `key`, and then returns it.
  5. *
  6. * @template K
  7. * @template V
  8. * @param {Map<K, V>} map
  9. * @param {K} key
  10. * @param {() => V} callback
  11. * @returns {V}
  12. */
  13. module.exports = function putIfAbsent(map, key, callback) {
  14. if (map.has(key)) return /** @type {V} */ (map.get(key));
  15. const value = callback();
  16. map.set(key, value);
  17. return value;
  18. };