object.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { parse as flatted_parse, stringify as flatted_stringify } from 'flatted';
  2. /** Structural equality via flatted serialization (handles cycles; key order matters). */
  3. export function isObjectsEqual(obj: unknown, obj2: unknown): boolean {
  4. return flatted_stringify(obj) == flatted_stringify(obj2)
  5. }
  6. export function cloneObject<T>(obj: T): T {
  7. return flatted_parse(flatted_stringify(obj))
  8. }
  9. export function deepEqual(obj1: any, obj2: any): boolean {
  10. if (obj1 === obj2) {
  11. return true;
  12. }
  13. if (typeof obj1 != "object" || obj1 === null ||
  14. typeof obj2 != "object" || obj2 === null) {
  15. return false;
  16. }
  17. let keys1 = Object.keys(obj1);
  18. let keys2 = Object.keys(obj2);
  19. if (keys1.length != keys2.length) {
  20. return false;
  21. }
  22. for (let key of keys1) {
  23. if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. export function mergeDeep(target: any, ...sources: any[]): any {
  30. if (!sources.length) return target;
  31. const source = sources.shift();
  32. if (isObject(target) && isObject(source)) {
  33. for (const key in source) {
  34. if (isObject(source[key])) {
  35. if (!target[key]) Object.assign(target, { [key]: {} });
  36. mergeDeep(target[key], source[key]);
  37. } else {
  38. Object.assign(target, { [key]: source[key] });
  39. }
  40. }
  41. }
  42. return mergeDeep(target, ...sources);
  43. }
  44. function isObject(item: unknown): item is Record<string, any> {
  45. return !!(item && typeof item === 'object' && !Array.isArray(item));
  46. }
  47. /** Parse a loose JS-style object literal (unquoted keys, single quotes); null on failure. */
  48. export function strToObj(s: string): any {
  49. try {
  50. const jsonReadyString = s
  51. .replace(/\s*([{}[\],:])\s*/g, '$1') // Remove spaces around {}, [], :, ,
  52. .replace(/([{,])([a-zA-Z0-9_]+)\s*:/g, '$1"$2":') // Wrap keys in double quotes
  53. .replace(/'/g, '"') // Replace single quotes with double quotes
  54. .replace(/,\s*}/g, '}') // Remove trailing commas before }
  55. .replace(/,\s*]/g, ']') // Remove trailing commas before ]
  56. .trim(); // Trim leading/trailing whitespace
  57. const a = JSON.parse(jsonReadyString);
  58. return a
  59. } catch (error) {
  60. return null
  61. }
  62. }
  63. export function filterContent(dataOrig: any, needed: string[]): any {
  64. let data = cloneObject(dataOrig);
  65. for (let cell in data.elements) {
  66. data.elements[cell] = data.elements[cell].filter((obj: any) => needed.includes(obj.source));
  67. }
  68. return data;
  69. }