Method: RichText::Delta#compose

Defined in:
lib/rich-text/delta.rb

#compose(other) ⇒ Delta Also known as: |

Returns a Delta that is equivalent to first applying the operations of self, then applying the operations of other on top of that.

Examples:

a = RichText::Delta.new.insert('abc')
b = RichText::Delta.new.retain(1).delete(1)
a.compose(b) # => #<RichText::Delta [insert="ac"]>

Parameters:

Returns:



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/rich-text/delta.rb', line 268

def compose(other)
  iter_a = Iterator.new(@ops)
  iter_b = Iterator.new(other.ops)
  delta = Delta.new
  while iter_a.next? || iter_b.next?
    if iter_b.peek.insert?
      delta.push(iter_b.next)
    elsif iter_a.peek.delete?
      delta.push(iter_a.next)
    else
      len = [iter_a.peek.length, iter_b.peek.length].min
      op_a = iter_a.next(len)
      op_b = iter_b.next(len)
      if op_b.retain?
        if op_a.retain?
          attrs = Attributes.compose(op_a.attributes, op_b.attributes, true)
          delta.push(Op.new(:retain, len, attrs))
        else
          attrs = Attributes.compose(op_a.attributes, op_b.attributes, false)
          delta.push(Op.new(:insert, op_a.value, attrs))
        end
      elsif op_b.delete? && op_a.retain?
        delta.push(op_b)
      end
    end
  end
  delta.chop!
end