UNPKG

string-differ

Version:

A Javascript library to compare and transform strings.

56 lines 1.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getOperations = void 0; const helpers_1 = require("./helpers"); function createOperations(type, helper, { a, b, store }) { const retainOp = (index) => helper.addOperation("retain", index); const insertOp = (index) => type === "Char" ? helper.addOperation("insert", b[index]) : helper.addOperation("insert", index); const deleteOp = (index) => helper.addOperation("delete", index); let x = a.length, y = b.length; for (let d = store.getSize() - 1; d > 0; d--) { const k = x - y; const prevK = d === -k || (d !== k && (store.get(d - 1, k + 1) ?? -1) > (store.get(d - 1, k - 1) ?? -1)) // prefer the move with larger x value ? k + 1 : k - 1; const prevX = store.get(d - 1, prevK) ?? -1; const prevY = prevX - prevK; // backtrack diagonal moves while (x > prevX && y > prevY) { x = x - 1; y = y - 1; retainOp(x); } if (x > prevX) { deleteOp(x - 1); } else { insertOp(y - 1); } x = prevX; y = prevY; } while (x !== 0 || y !== 0) { retainOp(--x); y -= 1; } return helper.getOperations(); } const getOperations = (type, context) => { switch (type) { case "Range": { return createOperations("Range", (0, helpers_1.RangeOperationsHelper)(context.b), context); } case "Char": { return createOperations("Char", (0, helpers_1.CharOperationsHelper)(), context); } default: { throw new Error("Unsupported operation type!"); } } }; exports.getOperations = getOperations; //# sourceMappingURL=backtrack.js.map