ToPropertyDescriptor.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var has = require('has');
  3. var GetIntrinsic = require('get-intrinsic');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var Type = require('./Type');
  6. var ToBoolean = require('./ToBoolean');
  7. var IsCallable = require('./IsCallable');
  8. // https://262.ecma-international.org/5.1/#sec-8.10.5
  9. module.exports = function ToPropertyDescriptor(Obj) {
  10. if (Type(Obj) !== 'Object') {
  11. throw new $TypeError('ToPropertyDescriptor requires an object');
  12. }
  13. var desc = {};
  14. if (has(Obj, 'enumerable')) {
  15. desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable);
  16. }
  17. if (has(Obj, 'configurable')) {
  18. desc['[[Configurable]]'] = ToBoolean(Obj.configurable);
  19. }
  20. if (has(Obj, 'value')) {
  21. desc['[[Value]]'] = Obj.value;
  22. }
  23. if (has(Obj, 'writable')) {
  24. desc['[[Writable]]'] = ToBoolean(Obj.writable);
  25. }
  26. if (has(Obj, 'get')) {
  27. var getter = Obj.get;
  28. if (typeof getter !== 'undefined' && !IsCallable(getter)) {
  29. throw new $TypeError('getter must be a function');
  30. }
  31. desc['[[Get]]'] = getter;
  32. }
  33. if (has(Obj, 'set')) {
  34. var setter = Obj.set;
  35. if (typeof setter !== 'undefined' && !IsCallable(setter)) {
  36. throw new $TypeError('setter must be a function');
  37. }
  38. desc['[[Set]]'] = setter;
  39. }
  40. if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
  41. throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
  42. }
  43. return desc;
  44. };