@bemoje/arr-sorted-index-of
v1.0.2
Published
Binary search -based indexOf for sorted arrays.
Downloads
27
Maintainers
Keywords
Readme
@bemoje/arr-sorted-index-of
Binary search -based indexOf for sorted arrays.
Version
Travis CI
Dependencies
Stats
Donate
Installation
npm install @bemoje/arr-sorted-index-of
npm install --save @bemoje/arr-sorted-index-of
npm install --save-dev @bemoje/arr-sorted-index-of
Usage
import arrSortedIndexOf from '@bemoje/arr-sorted-index-of'
const alpha = ['a', 'b', 'c']
arrSortedIndexOf(alpha, 'b')
//=> 1
arrSortedIndexOf(alpha, 'e')
//=> -1
const numeric = [2, 13, 20]
arrSortedIndexOf(numeric, 20, {
numeric: true,
})
//=> 2
arrSortedIndexOf(numeric, 20, (a, b) => {
return a - b
})
//=> 2
const arrays = [
[192, 168, 0, 0],
[192, 168, 0, 1],
[192, 168, 1, 0],
]
arrSortedIndexOf(arrays, [192, 168, 0, 1], {
numeric: true,
arrays: true,
})
//=> 1
let elem
const objectsByName = [
{ name: 'bonzo', age: 9 },
{ name: 'john', age: 7 },
]
elem = { name: 'john', age: 7 }
arrSortedIndexOf(objectsByName, elem, {
by: 'name',
})
//=> 1
const objectsByAge = [
{ name: 'john', age: 7 },
{ name: 'bonzo', age: 9 },
]
elem = { name: 'john', age: 7 }
arrSortedIndexOf(objectsByAge, elem, {
by: 'age',
})
//=> 0
const valuesByAge = [
['john', 7],
['bonzo', 9],
]
elem = ['bonzo', 9]
arrSortedIndexOf(objectsByAge, elem, {
by: 1,
})
//=> 1
const valuesByFirstInt = [
['john', 'johnson', 7],
['tracy', 'chapman', 9],
]
elem = ['tracy', 'chapman', 9]
arrSortedIndexOf(valuesByFirstInt, elem, {
by: (arrElem) => {
for (let val of arrElem) {
if (Number.isInteger(val)) {
return val
}
}
},
})
//=> 1
Tests
Uses Jest to test module functionality. Run tests to get coverage details.
npm run test
API
Table of Contents
arrSortedIndexOf
Binary search -based indexOf for sorted arrays.
Parameters
arr
Array The array to searchelement
any The element to findcompare
(comparator | object)?compare.numeric
boolean Sort numerically. Defaults to lexicographic/alphabetic sort. (optional, defaultfalse
)compare.descending
boolean Sort in descending order. Defaults to ascending order. (optional, defaultfalse
)compare.array
boolean Sort arrays. Nested arrays are also compared recursively. (optional, defaultfalse
)compare.by
(number | string | getter) Sort by either array index, a callback(element): any - or by object keys with dot-notation support. (optional, defaultundefined
)
Returns number Returns -1 if not found, if found, returns the elements index position.
comparator
Comparator function callback definition.
Type: Function
Parameters
a
any The first value to compareb
any The second value to compare
Returns number A negative number if a > b, a positive number if a < b, 0 otherwise.
getter
Callback type definition.
Type: Function
Parameters
a
any The value
Returns any The value to be compared