Replaceable.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _jestGetType = require('jest-get-type');
  7. /**
  8. * Copyright (c) Meta Platforms, Inc. and affiliates.
  9. *
  10. * This source code is licensed under the MIT license found in the
  11. * LICENSE file in the root directory of this source tree.
  12. */
  13. const supportTypes = ['map', 'array', 'object'];
  14. /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
  15. class Replaceable {
  16. object;
  17. type;
  18. constructor(object) {
  19. this.object = object;
  20. this.type = (0, _jestGetType.getType)(object);
  21. if (!supportTypes.includes(this.type)) {
  22. throw new Error(`Type ${this.type} is not support in Replaceable!`);
  23. }
  24. }
  25. static isReplaceable(obj1, obj2) {
  26. const obj1Type = (0, _jestGetType.getType)(obj1);
  27. const obj2Type = (0, _jestGetType.getType)(obj2);
  28. return obj1Type === obj2Type && supportTypes.includes(obj1Type);
  29. }
  30. forEach(cb) {
  31. if (this.type === 'object') {
  32. const descriptors = Object.getOwnPropertyDescriptors(this.object);
  33. [
  34. ...Object.keys(descriptors),
  35. ...Object.getOwnPropertySymbols(descriptors)
  36. ]
  37. //@ts-expect-error because typescript do not support symbol key in object
  38. //https://github.com/microsoft/TypeScript/issues/1863
  39. .filter(key => descriptors[key].enumerable)
  40. .forEach(key => {
  41. cb(this.object[key], key, this.object);
  42. });
  43. } else {
  44. this.object.forEach(cb);
  45. }
  46. }
  47. get(key) {
  48. if (this.type === 'map') {
  49. return this.object.get(key);
  50. }
  51. return this.object[key];
  52. }
  53. set(key, value) {
  54. if (this.type === 'map') {
  55. this.object.set(key, value);
  56. } else {
  57. this.object[key] = value;
  58. }
  59. }
  60. }
  61. /* eslint-enable */
  62. exports.default = Replaceable;