@bemoje/arr-sorted-insertion-index
v3.0.2
Published
Find the array index of where to add an element to keep it sorted.
Downloads
8
Maintainers
Keywords
Readme
@bemoje/arr-sorted-insertion-index
Find the array index of where to add an element to keep it sorted.
Version
Travis CI
Dependencies
Stats
Donate
Installation
npm install @bemoje/arr-sorted-insertion-index
npm install --save @bemoje/arr-sorted-insertion-index
npm install --save-dev @bemoje/arr-sorted-insertion-index
Usage
import arrSortedInsertionIndex from '@bemoje/arr-sorted-insertion-index'
/**
* FIND THE INDEX OF WHERE TO ADD AN ELEMENT TO KEEP IT SORTED
*/
const alpha = ['a', 'b', 'd', 'e']
arrSortedInsertionIndex(alpha, 'c')
//=> 2
/**
* ACCEPTS A CUSTOM COMPARATOR FUNCTION
* Compares numerically
*/
const numeric1 = [0, 1, 3, 4, 5]
arrSortedInsertionIndex(numeric1, 2, (a, b) => {
return a - b
})
//=> 3
/**
* ALSO TAKES ADVANCED COMPARATOR BUILDER OPTIONS
*/
const numeric2 = [0, 1, 3, 4, 5]
arrSortedInsertionIndex(numeric, 2, {
numeric: true,
})
//=> 3
/**
* DESCENDING EXAMPLE
*/
const descending = [5, 4, 3, 2, 0]
arrSortedInsertionIndex(descending, 1, {
numeric: true,
descending: true,
})
//=> 4
/**
* To see more examples of using the comparator builder, visit:
* https://github.com/bemoje/bemoje-arr-sort-comparator
*/
Tests
Uses Jest to test module functionality. Run tests to get coverage details.
npm run test
API
Table of Contents
arrSortedInsertionIndex
Find the array index of where to add an element to keep it sorted.
Parameters
arr
Array The arrayelement
any The element for which to find its insertion indexcompare.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 The insertion index
getter
Callback type definition.
Type: Function
Parameters
a
any The value
Returns any The value to be compared