Set.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var IsPropertyKey = require('./IsPropertyKey');
  4. var SameValue = require('./SameValue');
  5. var Type = require('./Type');
  6. // IE 9 does not throw in strict mode when writability/configurability/extensibility is violated
  7. var noThrowOnStrictViolation = (function () {
  8. try {
  9. delete [].length;
  10. return true;
  11. } catch (e) {
  12. return false;
  13. }
  14. }());
  15. // https://262.ecma-international.org/6.0/#sec-set-o-p-v-throw
  16. module.exports = function Set(O, P, V, Throw) {
  17. if (Type(O) !== 'Object') {
  18. throw new $TypeError('Assertion failed: `O` must be an Object');
  19. }
  20. if (!IsPropertyKey(P)) {
  21. throw new $TypeError('Assertion failed: `P` must be a Property Key');
  22. }
  23. if (typeof Throw !== 'boolean') {
  24. throw new $TypeError('Assertion failed: `Throw` must be a Boolean');
  25. }
  26. if (Throw) {
  27. O[P] = V; // eslint-disable-line no-param-reassign
  28. if (noThrowOnStrictViolation && !SameValue(O[P], V)) {
  29. throw new $TypeError('Attempted to assign to readonly property.');
  30. }
  31. return true;
  32. }
  33. try {
  34. O[P] = V; // eslint-disable-line no-param-reassign
  35. return noThrowOnStrictViolation ? SameValue(O[P], V) : true;
  36. } catch (e) {
  37. return false;
  38. }
  39. };