I'm seeking assistance in merging two arrays of nodes along with their decorations. My current algorithm is functional but highly inefficient. I would appreciate any suggestions for improvement or new ideas.
Each node within the arrays contains text, decorations (such as color and font styles), as well as 'from' and 'to' indexes. The goal is to combine these arrays while keeping the text intact and merging the decorations.
The existing algorithm involves iterating through each letter, checking for decorations, and creating a separate node for each letter with all applicable decorations:
const getDecorationsByIndex = (nodes, index) => {
const foundNodes: any[] = [];
nodes.forEach(node => {
if (index >= node.from && index < node.to) {
foundNodes.push(node);
}
});
return foundNodes.flatMap(node => node.textData?.decorations || []);
};
const mergeNodes = (nodes1, nodes2, content) => {
const mergedNodes = [...content].map((s, index) => {
const decorations1 = getDecorationsByIndex(nodes1, index);
const decorations2 = getDecorationsByIndex(nodes2, index);
return {
id: '',
nodes: [],
type: Node_Type.TEXT,
textData: {
decorations: [...decorations1, ...decorations2],
text: s,
},
};
});
return mergedNodes;
};
For example, consider a simple text "def" with various decorations ranging from color to font weight.
One array adds boldness to part of the text:
[
{
"type": "TEXT",
"id": "",
"nodes": [],
"textData": {
"text": "de",
"decorations": [
{
"type": "BOLD",
"fontWeightValue": 700
}
]
},
"from": 0,
"to": 2
},
{
"type": "TEXT",
"id": "",
"nodes": [],
"textData": {
"text": "f",
"decorations": []
},
"from": 2,
"to": 3
}
]
The second array introduces colors:
[
{
"id": "",
"nodes": [],
"type": "TEXT",
"textData": {
"decorations": [
{
"type": "COLOR",
"colorData": {
"foreground": "#d73a49"
}
}
],
"text": "def"
},
"from": 0,
"to": 3
}
]
The desired result should be:
[
{
"type": "TEXT",
"id": "",
"nodes": [],
"textData": {
"text": "de",
"decorations": [
{
"type": "BOLD",
"fontWeightValue": 700
},{
"type": "COLOR",
"colorData": {
"foreground": "#d73a49"
}
}
]
},
"from": 0,
"to": 2
},
{
"type": "TEXT",
"id": "",
"nodes": [],
"textData": {
"text": "f",
"decorations": [{
"type": "COLOR",
"colorData": {
"foreground": "#d73a49"
}
}]
},
"from": 2,
"to": 3
}
]
The final output should be one consolidated array of nodes preserving the original text along with all decorations. I'm open to suggestions on optimizing my algorithm or guidance on alternative approaches to tackle this node merging process. Thanks in advance!