mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Add enumerator chain feature (CRuby-2.6 compatible)
- Enumerator::Chain - Enumerable#chain - Enumerable#+
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
MRuby::Gem::Specification.new('mruby-enum-chain') do |spec|
|
||||
spec.license = 'MIT'
|
||||
spec.author = 'mruby developers'
|
||||
spec.summary = 'Enumerator::Chain class'
|
||||
spec.add_dependency('mruby-enumerator', :core => 'mruby-enumerator')
|
||||
end
|
||||
@@ -0,0 +1,60 @@
|
||||
##
|
||||
# chain.rb Enumerator::Chain class
|
||||
# See Copyright Notice in mruby.h
|
||||
|
||||
module Enumerable
|
||||
def chain(*args)
|
||||
Enumerator::Chain.new(self, *args)
|
||||
end
|
||||
|
||||
def +(other)
|
||||
Enumerator::Chain.new(self, other)
|
||||
end
|
||||
end
|
||||
|
||||
class Enumerator
|
||||
class Chain
|
||||
include Enumerable
|
||||
|
||||
def initialize(*args)
|
||||
@enums = args
|
||||
end
|
||||
|
||||
def initialize_copy(orig)
|
||||
@enums = orig.__copy_enums
|
||||
end
|
||||
|
||||
def each(&block)
|
||||
return to_enum unless block_given?
|
||||
|
||||
@enums.each { |e| e.each(&block) }
|
||||
|
||||
self
|
||||
end
|
||||
|
||||
def size
|
||||
@enums.reduce(0) do |a, e|
|
||||
return nil unless e.respond_to?(:size)
|
||||
a + e.size
|
||||
end
|
||||
end
|
||||
|
||||
def rewind
|
||||
@enums.reverse_each do |e|
|
||||
e.rewind if e.respond_to?(:rewind)
|
||||
end
|
||||
|
||||
self
|
||||
end
|
||||
|
||||
def inspect
|
||||
"#<#{self.class}: #{@enums.inspect}>"
|
||||
end
|
||||
|
||||
def __copy_enums
|
||||
@enums.each_with_object([]) do |e, a|
|
||||
a << e.clone
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user