Module: Ruwi::Utils::Arrays

Defined in:
lib/ruwi/runtime/utils/arrays.rb

Defined Under Namespace

Classes: ArrayWithOriginalIndices

Class Method Summary collapse

Class Method Details

.diff(old_array, new_array) ⇒ Hash

Returns Hash containing added and removed items.

Parameters:

  • old_array (Array)
  • new_array (Array)

Returns:

  • (Hash)

    Hash containing added and removed items



15
16
17
18
19
20
# File 'lib/ruwi/runtime/utils/arrays.rb', line 15

def self.diff(old_array, new_array)
  {
    added: (new_array - old_array).uniq,
    removed: (old_array - new_array).uniq
  }
end

.diff_sequence(old_array, new_array, equal_proc = ->(a, b) { a == b }) ⇒ Array

Returns sequence of operations to transform old_array into new_array.

Parameters:

  • old_array (Array)
  • new_array (Array)
  • equal_proc (Proc) (defaults to: ->(a, b) { a == b })

Returns:

  • (Array)

    sequence of operations to transform old_array into new_array



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/ruwi/runtime/utils/arrays.rb', line 150

def self.diff_sequence(old_array, new_array, equal_proc = ->(a, b) { a == b })
  sequence = []
  array = ArrayWithOriginalIndices.new(old_array, equal_proc)

  index = 0
  while index < new_array.length
    if array.is_removal?(index, new_array)
      sequence << array.remove_item(index)
      next
    end

    if array.is_noop?(index, new_array)
      sequence << array.noop_item(index)
      index += 1
      next
    end

    item = new_array[index]

    if array.is_addition?(item, index)
      sequence << array.add_item(item, index)
      index += 1
      next
    end

    sequence << array.move_item(item, index)
    index += 1
  end

  sequence.concat(array.remove_item_after(new_array.length))

  sequence
end

.without_nulls(arr) ⇒ Array

Parameters:

  • arr (Array)

Returns:

  • (Array)


8
9
10
# File 'lib/ruwi/runtime/utils/arrays.rb', line 8

def self.without_nulls(arr)
  arr.reject { |item| item.nil? }
end