mruby-enum-ext (sort_by): avoid copying the receiver

When the receiver is an Array.
This commit is contained in:
Yukihiro "Matz" Matsumoto
2024-07-03 07:31:32 +09:00
parent 7c7ee5c244
commit f1a04dae3e
+16 -12
View File
@@ -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