Skip to content

Commit

Permalink
Add Enumerable#{flat_map,collect_concat}
Browse files Browse the repository at this point in the history
  • Loading branch information
suzukaze committed Mar 21, 2014
1 parent 2c44f96 commit 44763eb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
30 changes: 30 additions & 0 deletions mrbgems/mruby-enum-ext/mrblib/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -237,4 +237,34 @@ def count(v=NONE, &block)
end
count
end

##
# call-seq:
# enum.flat_map { |obj| block } -> array
# enum.collect_concat { |obj| block } -> array
# enum.flat_map -> an_enumerator
# enum.collect_concat -> an_enumerator
#
# Returns a new array with the concatenated results of running
# <em>block</em> once for every element in <i>enum</i>.
#
# If no block is given, an enumerator is returned instead.
#
# [1, 2, 3, 4].flat_map { |e| [e, -e] } #=> [1, -1, 2, -2, 3, -3, 4, -4]
# [[1, 2], [3, 4]].flat_map { |e| e + [100] } #=> [1, 2, 100, 3, 4, 100]
def flat_map(&block)
return to_enum :flat_map unless block_given?

ary = []
self.each do |e|
e2 = block.call(e)
if e2.respond_to? :each
e2.each { |e3| ary.push(e3) }
else
ary.push(e2)
end
end
ary
end
alias collect_concat flat_map
end
6 changes: 6 additions & 0 deletions mrbgems/mruby-enum-ext/test/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,9 @@
assert_equal 2, a.count(2)
assert_equal 3, a.count{|x| x % 2 == 0}
end

assert("Enumerable#flat_map") do
assert_equal [1, 2, 3, 4], [1, 2, 3, 4].flat_map { |e| e }
assert_equal [1, -1, 2, -2, 3, -3, 4, -4], [1, 2, 3, 4].flat_map { |e| [e, -e] }
assert_equal [1, 2, 100, 3, 4, 100], [[1, 2], [3, 4]].flat_map { |e| e + [100] }
end

0 comments on commit 44763eb

Please sign in to comment.