Class: TransformableList
- Inherits:
-
Object
- Object
- TransformableList
- Defined in:
- lib/transformable_list.rb,
lib/transformable_list/version.rb
Constant Summary collapse
- VERSION =
"0.1.0"
Instance Method Summary collapse
-
#initialize(items, matcher: -> a, b { a == b }) ⇒ TransformableList
constructor
A new instance of TransformableList.
- #transform(new_items) ⇒ Object
Constructor Details
#initialize(items, matcher: -> a, b { a == b }) ⇒ TransformableList
Returns a new instance of TransformableList.
5 6 7 8 |
# File 'lib/transformable_list.rb', line 5 def initialize(items, matcher: -> a, b { a == b }) @items = items @matcher = matcher end |
Instance Method Details
#transform(new_items) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/transformable_list.rb', line 10 def transform(new_items) build_remaining_items_index! moves = [] creates = [] deletes = [] indexes_to_keep = Set.new new_items.map.with_index do |new_item, new_index| if existing_index = find_index_and_eliminate_match(new_item) if new_index != existing_index moves << [:move, @items[existing_index], new_index] end indexes_to_keep << existing_index else creates << [:create, new_item, new_index] end end (0...@items.size).each do |index| unless indexes_to_keep.include?(index) deletes << [:delete, @items[index], index] end end deletes.sort_by(&:last) + creates.sort_by(&:last) + moves.sort_by(&:last) end |