Replaceable.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _jestGetType = _interopRequireDefault(require('jest-get-type'));
  7. function _interopRequireDefault(obj) {
  8. return obj && obj.__esModule ? obj : {default: obj};
  9. }
  10. function _defineProperty(obj, key, value) {
  11. if (key in obj) {
  12. Object.defineProperty(obj, key, {
  13. value: value,
  14. enumerable: true,
  15. configurable: true,
  16. writable: true
  17. });
  18. } else {
  19. obj[key] = value;
  20. }
  21. return obj;
  22. }
  23. const supportTypes = ['map', 'array', 'object'];
  24. /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
  25. class Replaceable {
  26. constructor(object) {
  27. _defineProperty(this, 'object', void 0);
  28. _defineProperty(this, 'type', void 0);
  29. this.object = object;
  30. this.type = (0, _jestGetType.default)(object);
  31. if (!supportTypes.includes(this.type)) {
  32. throw new Error(`Type ${this.type} is not support in Replaceable!`);
  33. }
  34. }
  35. static isReplaceable(obj1, obj2) {
  36. const obj1Type = (0, _jestGetType.default)(obj1);
  37. const obj2Type = (0, _jestGetType.default)(obj2);
  38. return obj1Type === obj2Type && supportTypes.includes(obj1Type);
  39. }
  40. forEach(cb) {
  41. if (this.type === 'object') {
  42. const descriptors = Object.getOwnPropertyDescriptors(this.object);
  43. [
  44. ...Object.keys(descriptors),
  45. ...Object.getOwnPropertySymbols(descriptors)
  46. ] //@ts-expect-error because typescript do not support symbol key in object
  47. //https://github.com/microsoft/TypeScript/issues/1863
  48. .filter(key => descriptors[key].enumerable)
  49. .forEach(key => {
  50. cb(this.object[key], key, this.object);
  51. });
  52. } else {
  53. this.object.forEach(cb);
  54. }
  55. }
  56. get(key) {
  57. if (this.type === 'map') {
  58. return this.object.get(key);
  59. }
  60. return this.object[key];
  61. }
  62. set(key, value) {
  63. if (this.type === 'map') {
  64. this.object.set(key, value);
  65. } else {
  66. this.object[key] = value;
  67. }
  68. }
  69. }
  70. /* eslint-enable */
  71. exports.default = Replaceable;