1. /**
  2. * Synchronizes resources of text blocks, handling edge cases.
  3. *
  4. * @param {Array<object>} textBlocks An array of text block objects.
  5. * Each object should have a 'id' and 'content' property.
  6. * 'content' can be a string or an object containing resources.
  7. * @returns {Array<object>} The synchronized array of text block objects.
  8. */
  9. function syncTextBlockResources(textBlocks) {
  10. if (!Array.isArray(textBlocks)) {
  11. console.error("Input must be an array.");
  12. return []; // Return empty array for invalid input
  13. }
  14. const syncedBlocks = [];
  15. const resourceMap = new Map(); // Store resources by their unique identifiers
  16. for (const block of textBlocks) {
  17. if (!block || typeof block !== 'object' || !block.id || !block.content) {
  18. console.warn("Invalid text block encountered. Skipping.");
  19. continue; // Skip invalid blocks
  20. }
  21. const blockId = block.id;
  22. let synchronizedContent = block.content;
  23. if (typeof synchronizedContent === 'string') {
  24. synchronizedContent = synchronizedContent; // No change needed
  25. } else if (typeof synchronizedContent === 'object' && synchronizedContent !== null) {
  26. // Extract resources from the object
  27. if (synchronizedContent.resources) {
  28. const resources = synchronizedContent.resources;
  29. if (Array.isArray(resources)) {
  30. for (const resource of resources) {
  31. if (typeof resource === 'string' && !resourceMap.has(resource)) {
  32. resourceMap.set(resource, resource);
  33. } else if (typeof resource === 'object' && resource !== null) {
  34. //Handle objects as resources.
  35. if(!resourceMap.has(resource.id)){
  36. resourceMap.set(resource.id, resource);
  37. }
  38. }
  39. }
  40. }
  41. }
  42. }
  43. // Replace resource references with actual resource values
  44. if (typeof synchronizedContent === 'string') {
  45. for (const [id, resource] of resourceMap) {
  46. synchronizedContent = synchronizedContent.replace(new RegExp(`\\$\\{${id}\\}`, 'g'), resource);
  47. }
  48. } else if (typeof synchronizedContent === 'object' && synchronizedContent !== null) {
  49. for (const [id, resource] of resourceMap) {
  50. if (resource.id === id) {
  51. synchronizedContent = { ...synchronizedContent, [id]: resource };
  52. }
  53. }
  54. }
  55. syncedBlocks.push({ ...block, content: synchronizedContent });
  56. }
  57. return syncedBlocks;
  58. }

Add your comment