Skip to content

Instantly share code, notes, and snippets.

@alashstein
Last active October 20, 2023 04:04
Show Gist options
  • Save alashstein/13cbfcd5baaf909d2033bedea36fe63b to your computer and use it in GitHub Desktop.
Save alashstein/13cbfcd5baaf909d2033bedea36fe63b to your computer and use it in GitHub Desktop.
import copy
def convert_for_transform(op1, op2):
new_op_1 = {}
new_op_2 = {}
for j in op1:
for i in j:
if i == "retain":
op1_index = j[i]
new_op_1['index'] = op1_index
if i == "insert":
op1_char = j[i]
new_op_1['insert'] = op1_char
for j in op2:
for i in j:
if i == "retain":
op2_index = j[i]
new_op_2['index'] = op2_index
if i == "insert":
op2_char = j[i]
new_op_2['insert'] = op2_char
return new_op_1, new_op_2
def transform(op1, op2):
op1, op2 = convert_for_transform(op1, op2)
transform_type = []
if "insert" in op1:
transform_type.append('Ins')
if "insert" in op2:
transform_type.append('Ins')
sop1 = copy.deepcopy(op1)
sop2 = copy.deepcopy(op2)
if transform_type[0] == "Ins" and transform_type[1] == "Ins":
transformed_ops = insert_insert(op1, op2), insert_insert(sop2, sop1)
# Inserting characters at the same index.
# The fix is to make both operations agree on
# which one to insert first (order matters)
# so that they don't insert at different times.
if transformed_ops[0]['index'] == transformed_ops[1]['index']:
transformed_ops[0]['index'] = sop1['index']
return transformed_ops[0], transformed_ops[1]
def insert_insert(op1, op2):
if op1['index'] < op2['index']:
op1_prime = op1
else:
op1['index'] = op1['index'] + (len(op2['insert']))
op1_prime = op1
return op1_prime
# Example usage:
op1 = [{"retain": 0}, {"insert": "a\n"}]
op2 = [{"retain": 0}, {"insert": "O"}]
new_ops = transform(op1, op2, verbose=True)
print("Original op1:", op1)
print("Original op2:", op2)
print("Transformed op:", new_ops)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment