mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
mruby-enum-ext (sort_by): avoid copying the receiver
When the receiver is an Array.
This commit is contained in:
@@ -189,20 +189,9 @@ module Enumerable
|
||||
# values in <i>enum</i> through the given block.
|
||||
#
|
||||
# If no block is given, an enumerator is returned instead.
|
||||
|
||||
def sort_by(&block)
|
||||
return to_enum :sort_by unless block
|
||||
|
||||
ary = []
|
||||
orig = []
|
||||
self.each_with_index{|e, i|
|
||||
orig.push(e)
|
||||
ary.push([block.call(e), i])
|
||||
}
|
||||
if ary.size > 1
|
||||
ary.sort!
|
||||
end
|
||||
ary.collect{|e,i| orig[i]}
|
||||
self.to_a.sort_by(&block)
|
||||
end
|
||||
|
||||
##
|
||||
@@ -892,3 +881,18 @@ module Enumerable
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
class Array
|
||||
def sort_by(&block)
|
||||
return to_enum :sort_by unless block
|
||||
|
||||
ary = []
|
||||
self.each_with_index{|e, i|
|
||||
ary.push([block.call(e), i])
|
||||
}
|
||||
if ary.size > 1
|
||||
ary.sort!
|
||||
end
|
||||
ary.collect!{|e,i| self[i]}
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user