invert method
Inverts this delta against base
.
Returns new delta which negates effect of this delta when applied to
base
. This is an equivalent of "undo" operation on deltas.
Implementation
Delta invert(Delta base) {
final inverted = new Delta();
if (base.isEmpty) return inverted;
int baseIndex = 0;
for (final op in _operations) {
if (op.isInsert) {
inverted.delete(op.length!);
} else if (op.isRetain && op.isPlain) {
inverted.retain(op.length!, null);
baseIndex += op.length!;
} else if (op.isDelete || (op.isRetain && op.isNotPlain)) {
final length = op.length!;
final sliceDelta = base.slice(baseIndex, baseIndex + length);
sliceDelta.toList().forEach((baseOp) {
if (op.isDelete) {
inverted.push(baseOp);
} else if (op.isRetain && op.isNotPlain) {
var invertAttr = invertAttributes(op.attributes, baseOp.attributes);
inverted.retain(baseOp.length!, invertAttr.isEmpty ? null : invertAttr);
}
});
baseIndex += length;
} else {
throw StateError("Unreachable");
}
}
inverted.trim();
return inverted;
}