summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext/mrblib/array.rb
diff options
context:
space:
mode:
authorChristopher Aue <[email protected]>2017-07-28 17:02:36 +0200
committerChristopher Aue <[email protected]>2017-07-28 23:51:40 +0200
commit451574f1420d8533f44a06d9aca23b5647292228 (patch)
tree9d298926a859fbd9733e3dceed37166780ecd0e1 /mrbgems/mruby-array-ext/mrblib/array.rb
parent8a6ce74b4d33b804edd4d2bb281a45a414bcc62f (diff)
downloadmruby-451574f1420d8533f44a06d9aca23b5647292228.tar.gz
mruby-451574f1420d8533f44a06d9aca23b5647292228.zip
Refactored Array#bsearch
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb34
1 files changed, 20 insertions, 14 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 1e6d4d581..b5c2e7c47 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -596,30 +596,36 @@ class Array
return to_enum :bsearch unless block_given?
low = 0
- high = self.size
+ high = size
satisfied = false
+
while low < high
- mid = low + ((high - low) / 2).truncate
+ mid = ((low+high)/2).truncate
val = self[mid]
- v = block.call(val)
- if v.is_a?(Integer)
- return val if v == 0
- smaller = v < 0
- elsif v == true
+ res = block.call val
+
+ case res
+ when 0 # find-any mode: Found!
+ return val
+ when Numeric # find-any mode: Continue...
+ in_lower_half = res < 0
+ when true # find-min mode
+ in_lower_half = true
satisfied = true
- smaller = true
- elsif v == false || v.nil?
- smaller = false
+ when false, nil # find-min mode
+ in_lower_half = false
+ else
+ raise TypeError, 'invalid block result (must be numeric, true, false or nil)'
end
- if smaller
+
+ if in_lower_half
high = mid
else
low = mid + 1
end
end
- return nil if low == self.size
- return nil unless satisfied
- self[low]
+
+ satisfied ? self[low] : nil
end
##