Search code examples
javascriptpythonbisection

Javascript's equivalent of R's findInterval() or Python's bisect.bisect_left


I can't find how to determine to which interval an element belongs based on an Array for JavaScript. I want the behavior of bisect.bisect_left from Python. Here is some sample code:

import bisect
a = [10,20,30,40]
print(bisect.bisect_left(a,0))  #0  because 0 <= 10
print(bisect.bisect_left(a,10)) #0  because 10 <= 10
print(bisect.bisect_left(a,15)) #1  because 10 < 15 < 20
print(bisect.bisect_left(a,25)) #2  ...
print(bisect.bisect_left(a,35)) #3  ...
print(bisect.bisect_left(a,45)) #4

I know this would be easy to implement, but why re-invent the wheel?


Solution

  • There are no built-in bisection functions in JavaScript, so you will have to roll your own. Here is my personal reinvention of the wheel:

    var array = [10, 20, 30, 40]
    
    function bisectLeft (array, x) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] >= x) return i
      }
      return array.length
    }
    
    console.log(bisectLeft(array, 5))
    console.log(bisectLeft(array, 15))
    console.log(bisectLeft(array, 25))
    console.log(bisectLeft(array, 35))
    console.log(bisectLeft(array, 45))
    
    function bisectRight (array, x) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] > x) return i
      }
      return array.length
    }