map-upsert.js 1.0 KB

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