/**
* Synchronizes resources of text blocks, handling edge cases.
*
* @param {Array<object>} textBlocks An array of text block objects.
* Each object should have a 'id' and 'content' property.
* 'content' can be a string or an object containing resources.
* @returns {Array<object>} The synchronized array of text block objects.
*/
function syncTextBlockResources(textBlocks) {
if (!Array.isArray(textBlocks)) {
console.error("Input must be an array.");
return []; // Return empty array for invalid input
}
const syncedBlocks = [];
const resourceMap = new Map(); // Store resources by their unique identifiers
for (const block of textBlocks) {
if (!block || typeof block !== 'object' || !block.id || !block.content) {
console.warn("Invalid text block encountered. Skipping.");
continue; // Skip invalid blocks
}
const blockId = block.id;
let synchronizedContent = block.content;
if (typeof synchronizedContent === 'string') {
synchronizedContent = synchronizedContent; // No change needed
} else if (typeof synchronizedContent === 'object' && synchronizedContent !== null) {
// Extract resources from the object
if (synchronizedContent.resources) {
const resources = synchronizedContent.resources;
if (Array.isArray(resources)) {
for (const resource of resources) {
if (typeof resource === 'string' && !resourceMap.has(resource)) {
resourceMap.set(resource, resource);
} else if (typeof resource === 'object' && resource !== null) {
//Handle objects as resources.
if(!resourceMap.has(resource.id)){
resourceMap.set(resource.id, resource);
}
}
}
}
}
}
// Replace resource references with actual resource values
if (typeof synchronizedContent === 'string') {
for (const [id, resource] of resourceMap) {
synchronizedContent = synchronizedContent.replace(new RegExp(`\\$\\{${id}\\}`, 'g'), resource);
}
} else if (typeof synchronizedContent === 'object' && synchronizedContent !== null) {
for (const [id, resource] of resourceMap) {
if (resource.id === id) {
synchronizedContent = { ...synchronizedContent, [id]: resource };
}
}
}
syncedBlocks.push({ ...block, content: synchronizedContent });
}
return syncedBlocks;
}
Add your comment