binarysearch
pure js binary search for sorted javascript arrays||array like objects. returns any || last || first || closest matched key for value, or slice between 2 values where values need not exist.
returns the matched key or -1 if not found.
example
var bs = ; === 2//true === -1// true
search with user defined comparator function
=== 4// true
find first key that matches
bs === 3
find last key that matches
bs === 5
find closest key to where or key of searched value in the array
- if the key is in the array the key will point to
- the first key that has that value by default
- the last key that has that value if {end:true} option is specified
- only returns -1 if array is empty
bs === 1bs === 0bs === 6 // non unique matching/matching at end of seriesbs === 3bs === 5
query for rangeValue (inclusive). returns sliced values.
bs === 33344
or simply access the array offsets directly as [start,end]
bs === 26
insert a value into a sorted array.
var arr = 134;bs === 1// returns the key it inserted into arr1 === 2// true
when you insert values and there are duplicates the default behavior is to insert the new value after the other same values. if you pass option.unique = true the key's value is replaced with the new value
var arr = 123;bs// arr is [1,2,2,3] var arr = 123;bs;// arr is [1,2,3]
insert with user defined comparator function
var arr = 56789;bs;// arr is [5,6,7,8,9,10]
create an object index
var index = bs;// [{k:'b',v:1},{k:a,v:2}];
search an object index
var obj = a:id:22name:'bob'b:id:11name:'joe';// [{k:'b',v:11},{k:'a',v:22}]; index = bs; objk === id:22name:'bob';