putIfAbsent.mjs 464 B

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