invert method

Delta invert(
  1. Delta base
)

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 = Delta();
  if (base.isEmpty) return inverted;

  var baseIndex = 0;
  for (final op in operations) {
    if (op.isInsert) {
      inverted.delete(op.length!);
    } else if (op.isRetain && op.isPlain) {
      inverted.retain(op.length!);
      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) {
          final invertAttr =
              invertAttributes(op.attributes, baseOp.attributes);
          inverted.retain(
              baseOp.length!, invertAttr.isEmpty ? null : invertAttr);
        }
      });
      baseIndex += length;
    } else {
      throw StateError('Unreachable');
    }
  }
  inverted.trim();
  return inverted;
}