Last active
September 26, 2019 10:43
-
-
Save garmoshka-mo/98e844d87d316dd34f0cb8a53b216af0 to your computer and use it in GitHub Desktop.
lib/iterations_sugar.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module IterationsSugar | |
def extract | |
result = ActiveArray.new | |
each_with_index do |item, index| | |
e = yield item, index | |
result << e unless e.nil? | |
end | |
result | |
end | |
def extract_map | |
result = Hash.new | |
each_with_index do |item, index| | |
e = yield item, index | |
result[item] = e unless e.nil? | |
end | |
result | |
end | |
def extract_one | |
hide_from_stack = true | |
each_with_index do |item, index| | |
result = yield item, index | |
return result if result | |
end | |
nil | |
end | |
def expand(method) | |
hide_from_stack = true | |
result = ActiveArray.new | |
each do |item| | |
result.merge item.send(method) | |
end | |
result | |
end | |
def max_value | |
max = nil | |
each do |item| | |
value = yield item | |
if not max or (value and value > max) | |
max = value | |
end | |
end | |
max | |
end | |
end | |
Set.class_eval do | |
include IterationsSugar | |
end | |
Array.class_eval do | |
include IterationsSugar | |
alias some? any? | |
alias index_of find_index | |
alias filter select | |
alias remove delete | |
def merge(other) | |
if other.is_a? Array | |
self.concat other | |
else | |
self << other | |
end | |
end | |
def merge_uniq(other) | |
other.each do |element| | |
self << element unless include? element | |
end | |
end | |
def intersects?(other) | |
not (self & other).empty? | |
end | |
def find!(&block) | |
find(&block) || error("Not found") | |
end | |
# fix compact! to act properly | |
alias original_compact! compact! | |
def compact! | |
original_compact! | |
self | |
end | |
def add?(value) | |
self << value if value | |
end | |
def single! | |
r = take_the_only | |
error 'Нет элемента, а нужен' if r.nil? | |
r | |
end | |
def take_the_only | |
if count > 1 | |
error "Много объектов, а нужно не больше одного: #{self}" | |
end | |
first | |
end | |
def find_class(cls) | |
hide_from_stack = true | |
find { |item| item.is_a? cls } | |
end | |
alias some_is_a? find_class | |
alias has_class? find_class | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment