serialization.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @fileoverview Serialization utils.
  3. * @author Bryan Mishkin
  4. */
  5. "use strict";
  6. /**
  7. * Check if a value is a primitive or plain object created by the Object constructor.
  8. * @param {any} val the value to check
  9. * @returns {boolean} true if so
  10. * @private
  11. */
  12. function isSerializablePrimitiveOrPlainObject(val) {
  13. return (
  14. val === null ||
  15. typeof val === "string" ||
  16. typeof val === "boolean" ||
  17. typeof val === "number" ||
  18. (typeof val === "object" && val.constructor === Object) ||
  19. Array.isArray(val)
  20. );
  21. }
  22. /**
  23. * Check if a value is serializable.
  24. * Functions or objects like RegExp cannot be serialized by JSON.stringify().
  25. * Inspired by: https://stackoverflow.com/questions/30579940/reliable-way-to-check-if-objects-is-serializable-in-javascript
  26. * @param {any} val the value
  27. * @returns {boolean} true if the value is serializable
  28. */
  29. function isSerializable(val) {
  30. if (!isSerializablePrimitiveOrPlainObject(val)) {
  31. return false;
  32. }
  33. if (typeof val === "object") {
  34. for (const property in val) {
  35. if (Object.hasOwn(val, property)) {
  36. if (!isSerializablePrimitiveOrPlainObject(val[property])) {
  37. return false;
  38. }
  39. if (typeof val[property] === "object") {
  40. if (!isSerializable(val[property])) {
  41. return false;
  42. }
  43. }
  44. }
  45. }
  46. }
  47. return true;
  48. }
  49. module.exports = {
  50. isSerializable
  51. };