Set.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var isPropertyKey = require('../helpers/isPropertyKey');
  4. var SameValue = require('./SameValue');
  5. var isObject = require('../helpers/isObject');
  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 (!isObject(O)) {
  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. };