Skip to content

Commit

Permalink
Implementation and test of Enumerable#with_position
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Dec 22, 2016
1 parent c58defb commit ee05fa8
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
58 changes: 58 additions & 0 deletions lib/core/facets/enumerable/with_position.rb
@@ -0,0 +1,58 @@

module Enumerable
class Position
def initialize
@first = true
@last = false
end

def after_first!
@first = false
end

def at_end!
@last = true
end

def first?
@first
end

def middle?
not (@first or @last)
end

def last?
@last
end
end

# Allows one to know the position of the enumeration easily.
#
# 5.times.collect.with_position do |i, position|
# $stdout.write "#{i}#{position.middle? ? ',' : ''}"
# end
#
# Where this becomes more useful, is when it's easy to determine the position of elements, e.g.
#
# 10.times.select(&:odd?).with_position{|n,p| ... }
#
def with_position
return to_enum(:with_position) unless block_given?

position = Position.new

while item = self.next
begin
self.peek
rescue StopIteration
position.at_end!
end

yield item, position.dup

position.after_first!
end
rescue StopIteration
end
end
42 changes: 42 additions & 0 deletions test/core/enumerable/test_with_position.rb
@@ -0,0 +1,42 @@
covers 'facets/enumerable/with_position'

test_case Enumerable do

method :with_position do

test do
a = 5.times.with_position.to_a

item, position = a.first
item.assert == 0
assert position.first?
refute position.middle?
refute position.last?


item, position = a[2]
item.assert == 2
assert position.middle?
refute position.first?
refute position.last?

item, position = a.last
item.assert == 4
refute position.first?
refute position.middle?
assert position.last?
end

test do
a = 1.times.with_position.to_a

item, position = a.first
item.assert == 0
assert position.first?
refute position.middle?
assert position.last?
end

end

end

0 comments on commit ee05fa8

Please sign in to comment.