Sha256: 04ca9771dfe27e8f8b1a4c878fc86ec55636bb137026eac3f48398f533145d70

Contents?: true

Size: 1.26 KB

Versions: 38

Compression:

Stored size: 1.26 KB

Contents

unless Range.method_defined? :bsearch
  require 'backports/tools/float_integer_conversion'

  class Range
    def bsearch
      return to_enum(:bsearch) unless block_given?
      from = self.begin
      to   = self.end
      unless from.is_a?(Numeric) && to.is_a?(Numeric)
        raise TypeError, "can't do binary search for #{from.class}"
      end

      midpoint = nil
      if from.is_a?(Integer) && to.is_a?(Integer)
        convert = Proc.new{ midpoint }
      else
        from = Backports.float_to_integer(from.to_f)
        to   = Backports.float_to_integer(to.to_f)
        convert = Proc.new{ Backport.integer_to_float(midpoint) }
      end
      to -= 1 if exclude_end?
      satisfied = nil
      while from <= to do
        midpoint = (from + to).div(2)
        result = yield(cur = convert.call)
        case result
        when Numeric
          return cur if result == 0
          result = result < 0
        when true
          satisfied = cur
        when nil, false
          # nothing to do
        else
          raise TypeError, "wrong argument type #{result.class} (must be numeric, true, false or nil)"
        end

        if result
          to = midpoint - 1
        else
          from = midpoint + 1
        end
      end
      satisfied
    end
  end
end

Version data entries

38 entries across 38 versions & 3 rubygems

Version Path
backports-3.25.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.24.1 lib/backports/2.0.0/range/bsearch.rb
backports-3.24.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.23.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.22.1 lib/backports/2.0.0/range/bsearch.rb
backports-3.22.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.21.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.20.2 lib/backports/2.0.0/range/bsearch.rb
backports-3.20.1 lib/backports/2.0.0/range/bsearch.rb
backports-3.20.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.19.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.18.2 lib/backports/2.0.0/range/bsearch.rb
backports-3.18.1 lib/backports/2.0.0/range/bsearch.rb
backports-3.18.0 lib/backports/2.0.0/range/bsearch.rb
files.com-1.0.55 docs/vendor/bundle/ruby/2.5.0/gems/backports-3.12.0/lib/backports/2.0.0/range/bsearch.rb
backports-3.17.2 lib/backports/2.0.0/range/bsearch.rb
backports-3.17.1 lib/backports/2.0.0/range/bsearch.rb
backports-3.17.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.16.1 lib/backports/2.0.0/range/bsearch.rb
backports-3.16.0 lib/backports/2.0.0/range/bsearch.rb