bfind
Runs a binary search on any sorted collection.
Installation
Requires Node.js 8.3.0 or above.
npm i bfind
API
The module exports a single function.
Parameters
- Object argument:
- Optional:
compare
(function, array, or any):- If a function: When passed two arguments
a
andb
, expected to return-1
ifa
is less thanb
,1
ifa
is greater thanb
, and0
if they are equal. - If an array: An array of Map/object keys, the values of which can be used to compare two Maps/objects. The first key is checked first, and if the two values for that key are equal, the next key in the array is checked, and so on. If any given element is itself an array, it is interpreted as a nested keychain.
- Otherwise: A single Map/object key.
- If omitted: Only numbers and strings will be compared as-is. All others values will be coerced into strings before being compared.
- If a function: When passed two arguments
get
(function): A callback that should return a value from the collection for a given index from0
tolength - 1
.length
(positive integer): The length of the collection.- Optional:
multiple
(string): Specifies behavior in the event that more than one existing collection item is sort-equivalent withvalue
.- If set to
first
orlast
, the index of the first or last sort-equivalent item (respectively) will be returned. - If set to
identical
, every sort-equivalent item will be scanned for identity (===
) withvalue
and the first identical item found will have its index returned. - Otherwise, the index of whatever sort-equivalent item the algorithm comes across first will be returned.
- If set to
value
(any): The value to search for.
- Optional:
Return Value
Returns an object:
found
(boolean):true
ifcompare
reported that the collection contains another value with the same sort value asvalue
;false
otherwise.index
(positive integer): The index ofvalue
or its sort-equivalent (ifequal
istrue
); or, the appropriate insertion index forvalue
(ifequal
isfalse
).
Example
const bfind = const arr = 'a' 'c' 'c' const argsForArr = arri length: arrlength // {found: true, index: 0} // {found: false, index: 1} // {found: true, index: 1} // {found: true, index: 2}
Related
This module is part of the “b” family of binary search modules.