map-upsert.js 721 B

1234567891011121314151617181920212223
  1. 'use strict';
  2. var anObject = require('../internals/an-object');
  3. // `Map.prototype.upsert` method
  4. // https://github.com/thumbsupep/proposal-upsert
  5. module.exports = function upsert(key, updateFn /* , insertFn */) {
  6. var map = anObject(this);
  7. var insertFn = arguments.length > 2 ? arguments[2] : undefined;
  8. var value;
  9. if (typeof updateFn != 'function' && typeof insertFn != 'function') {
  10. throw TypeError('At least one callback required');
  11. }
  12. if (map.has(key)) {
  13. value = map.get(key);
  14. if (typeof updateFn == 'function') {
  15. value = updateFn(value);
  16. map.set(key, value);
  17. }
  18. } else if (typeof insertFn == 'function') {
  19. value = insertFn();
  20. map.set(key, value);
  21. } return value;
  22. };