Binary search: Equal & closest search in sorted array.
npm install @jollie/binary-search




Equal or closest search in sorted array using binary search algorithm.
See https://en.wikipedia.org/wiki/Binary_search_algorithm#Procedure
Binary search is faster than linear search (except for small array ...).
``bash`
yarn add @jollie/binary-search
or
`bash`
npm install @jollie/binary-search
`javascript
import { equalSearch, closestSearch } from '@jollie/binary-search';
// Equal search in numeric array
equalSearch([1, 2, 3], 2); // Found -> Output 1
equalSearch([1, 2, 3], 5); // Not found -> Output -1
// Equal search in string array
equalSearch(['a', 'b', 'c'], 'c'); // Found -> Output 2
equalSearch(['a', 'b', 'c'], '?'); // Not found -> Output -1
// Closest search
closestSearch([1, 2, 3], 2.2); // Output 1
closestSearch([1, 2, 3], 2.6); // Output 2
closestSearch([1, 2, 3], -1); // Output 0
closestSearch([1, 2, 3], 1000); // Output 2
`
`javascript`
equalSearch(haystack, needle[, { compare, from, to }]);
closestSearch(haystack, needle[, { compare, from, to }]);
| Prop | Type | Default | Note |
|:-----------|:------------|:-------------------------------------|:------|
| haystack | array | mandatory | Array of values needle
| | any | mandatory | Searched valuecompare
| | function | (needle, value) => needle - value | Compare function. (a, b) => a.localeCompare(b)
Special case for equalSearch:
if needle is a string, default compare isfrom
| | integer | 0 | Start index for range searchingto
| | integer | haystack.length - 1 | End index for range searching
Index in the array or -1 if not found
Throw RangerError if from or to` are outbounds