summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-range-ext
diff options
context:
space:
mode:
authorRyan Lopopolo <[email protected]>2019-07-09 01:42:40 -0700
committerRyan Lopopolo <[email protected]>2019-07-09 01:42:40 -0700
commit0ad5ba7a0f819cff87460d9b6f5691656ea75ade (patch)
treeec035ae72c7368902eeea3e906fcece23e88d6c7 /mrbgems/mruby-range-ext
parenteab07daf92c9a8a2836923656d9e8f58583a52ba (diff)
downloadmruby-0ad5ba7a0f819cff87460d9b6f5691656ea75ade.tar.gz
mruby-0ad5ba7a0f819cff87460d9b6f5691656ea75ade.zip
Add a fast path for Float and Fixnum ranges for Range#max and Range#min
If no block is given and the Range has Fixnum or Float endpoints, do not iterate with each and instead compare the endpoints directly. This implementation passes all of the applicable specs from Ruby Spec.
Diffstat (limited to 'mrbgems/mruby-range-ext')
-rw-r--r--mrbgems/mruby-range-ext/mrblib/range.rb40
1 files changed, 40 insertions, 0 deletions
diff --git a/mrbgems/mruby-range-ext/mrblib/range.rb b/mrbgems/mruby-range-ext/mrblib/range.rb
index de7925ba7..e09b2d096 100644
--- a/mrbgems/mruby-range-ext/mrblib/range.rb
+++ b/mrbgems/mruby-range-ext/mrblib/range.rb
@@ -25,4 +25,44 @@ class Range
end
ary
end
+
+ def max(&block)
+ val = self.first
+ last = self.last
+ return super if block
+
+ # fast path for numerics
+ if (val.kind_of?(Fixnum) || val.kind_of?(Float)) && (last.kind_of?(Fixnum) || last.kind_of?(Float))
+ raise TypeError if exclude_end? && !last.kind_of?(Fixnum)
+ return nil if val > last
+ return nil if val == last && exclude_end?
+
+ max = last
+ max -= 1 if exclude_end?
+ return max
+ end
+
+ # delegate to Enumerable
+ super
+ end
+
+ def min(&block)
+ val = self.first
+ last = self.last
+ return super if block
+
+ # fast path for numerics
+ if (val.kind_of?(Fixnum) || val.kind_of?(Float)) && (last.kind_of?(Fixnum) || last.kind_of?(Float))
+ raise TypeError if exclude_end? && !last.kind_of?(Fixnum)
+ return nil if val > last
+ return nil if val == last && exclude_end?
+
+ min = val
+ min -= 1 if exclude_end?
+ return min
+ end
+
+ # delegate to Enumerable
+ super
+ end
end