"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.chunk = exports.normalize = exports.trim = exports.isDeleteComponent = exports.componentLength = exports.append = void 0;
const append = (op, component) => {
    if (!component)
        return;
    if (!op.length) {
        op.push(component);
        return;
    }
    const lastIndex = op.length - 1;
    const last = op[lastIndex];
    if (typeof component === 'number') {
        if (typeof last === 'number') {
            if (component > 0 && last > 0)
                op[lastIndex] = last + component;
            else if (component < 0 && last < 0)
                op[lastIndex] = last + component;
            else
                op.push(component);
        }
        else
            op.push(component);
    }
    else if (component instanceof Uint8Array) {
        if (last instanceof Uint8Array) {
            const combined = new Uint8Array(last.length + component.length);
            combined.set(last, 0);
            combined.set(component, last.length);
            op[lastIndex] = combined;
        }
        else
            op.push(component);
    }
};
exports.append = append;
const componentLength = (component) => {
    return typeof component === 'number' ? Math.abs(component) : component.length;
};
exports.componentLength = componentLength;
const isDeleteComponent = (component) => {
    return typeof component === 'number' && component < 0;
};
exports.isDeleteComponent = isDeleteComponent;
const trim = (op) => {
    if (!op.length)
        return;
    const last = op[op.length - 1];
    const isLastRetain = typeof last === 'number' && last > 0;
    if (isLastRetain)
        op.pop();
};
exports.trim = trim;
const normalize = (op) => {
    const op2 = [];
    const length = op.length;
    for (let i = 0; i < length; i++)
        (0, exports.append)(op2, op[i]);
    (0, exports.trim)(op2);
    return op2;
};
exports.normalize = normalize;
/**
 * Extracts a full or a part of a component from an operation.
 *
 * @param component Component from which to extract a chunk.
 * @param offset Position within the component to start from.
 * @param maxLength Maximum length of the component to extract.
 * @returns Full or partial component at index `index` of operation `op`.
 */
const chunk = (component, offset, maxLength) => {
    if (typeof component === 'number') {
        return component > 0 ? Math.min(component - offset, maxLength) : -Math.min(-component - offset, maxLength);
    }
    else if (component instanceof Uint8Array) {
        const end = Math.min(offset + maxLength, component.length);
        return component.subarray(offset, end);
    }
    return component;
};
exports.chunk = chunk;
//# sourceMappingURL=util.js.map