map-upsert.js 997 B

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