Set.js 1.2 KB

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