JSFiddle - React, Tailwind, and code Playground

by Digvijay Naruka

JavaScript

function optimizeOps(ops) {
    let optimizedOps = [];
    let currentOp = null;

    ops.forEach(op => {
        // If there's no current operation, set the current operation
        if (!currentOp) {
            currentOp = {
                attributes: op.attributes || {},
                insert: Array.isArray(op.insert) ? op.insert : [op.insert]
            };
        } else {
            // Compare attributes of current operation with the new one
            const sameAttributes = JSON.stringify(currentOp.attributes) === JSON.stringify(op.attributes || {});

            if (sameAttributes) {
                // If attributes are the same, merge the insert property
                currentOp.insert.push(op.insert);
            } else {
                // Otherwise, push the current operation to the optimized list and start a new one
                optimizedOps.push(currentOp);
                currentOp = {
                    attributes: op.attributes || {},
                    insert: Array.isArray(op.insert) ? op.insert : [op.insert]
                };
            }
        }
    });

    // Push the last operation
    if (currentOp) {
        optimizedOps.push(currentOp);
    }

    return optimizedOps;
}
ops = [
    {
        "attributes": {
            "excluded": true
        },
        "insert": "Table of "
    },
    {
        "insert": "neo"
    },
    {
        "attributes": {
            "excluded": true
        },
        "insert": "pla"
    },
    {
        "attributes": {
            "excluded": true
        },
        "insert": {
            "sep": ","
        }
    },
    {
        "attributes": {
            "excluded": true
        },
        "insert": "s"
    },
    {
        "insert": "m"
    },
    {
        "attributes": {
            "hidden": true
        },
        "insert": {
            "sep": ","
        }
    },
    {
        "attributes": {
            "hidden": true
        },
        "insert": " neoplasm"
    },
    {
       ...