You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.6 KiB
67 lines
1.6 KiB
class ArrayProcessor
|
|
def initialize(array)
|
|
@array = array.dup.freeze
|
|
end
|
|
|
|
# Возвращает элементы массива
|
|
def elements
|
|
@array
|
|
end
|
|
|
|
# группировка элементов
|
|
def chunk
|
|
raise "No block given" unless block_given?
|
|
|
|
result = []
|
|
current_group = []
|
|
@array.each do |element|
|
|
if current_group.empty? || yield(element) == yield(current_group.last)
|
|
current_group << element
|
|
else
|
|
result << current_group
|
|
current_group = [element]
|
|
end
|
|
end
|
|
result << current_group unless current_group.empty?
|
|
result
|
|
end
|
|
|
|
# проверка наличия элемента
|
|
def include?(value)
|
|
@array.each do |element|
|
|
return true if element == value
|
|
end
|
|
false
|
|
end
|
|
|
|
# свёртка массива
|
|
def reduce(initial = nil)
|
|
raise "No block given" unless block_given?
|
|
|
|
accumulator = initial
|
|
@array.each do |element|
|
|
if accumulator.nil?
|
|
accumulator = element
|
|
else
|
|
accumulator = yield(accumulator, element)
|
|
end
|
|
end
|
|
accumulator
|
|
end
|
|
|
|
# проверка членства
|
|
def member?(value)
|
|
include?(value)
|
|
end
|
|
|
|
# фильтрация массива
|
|
def filter
|
|
raise "No block given" unless block_given?
|
|
|
|
result = []
|
|
@array.each do |element|
|
|
result << element if yield(element)
|
|
end
|
|
result
|
|
end
|
|
end |