ToPropertyDescriptor.js 1.4 KB

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