map-emplace.js 739 B

123456789101112131415161718192021222324
  1. 'use strict';
  2. var call = require('../internals/function-call');
  3. var aCallable = require('../internals/a-callable');
  4. var anObject = require('../internals/an-object');
  5. // `Map.prototype.emplace` method
  6. // https://github.com/thumbsupep/proposal-upsert
  7. module.exports = function emplace(key, handler) {
  8. var map = anObject(this);
  9. var get = aCallable(map.get);
  10. var has = aCallable(map.has);
  11. var set = aCallable(map.set);
  12. var value, inserted;
  13. if (call(has, map, key)) {
  14. value = call(get, map, key);
  15. if ('update' in handler) {
  16. value = handler.update(value, key, map);
  17. call(set, map, key, value);
  18. } return value;
  19. }
  20. inserted = handler.insert(key, map);
  21. call(set, map, key, inserted);
  22. return inserted;
  23. };