Binary sorted array. Implements array initialization, insertion, finding index of element, item removal, clearing the array.
npm install binary-sorted-arrayindexOf or insert (to find position in the array where the item should be inserted).
lib/index.js file
npm i --save binary-sorted-array
javascript
import BinarySortedArray from 'binary-sorted-array'
let array = new BinarySortedArray([1, 5, 6, 3, 5, 1])
array.insert(0.99)
array.remove(3)
array.indexOf(6)
let sortedArray = array.getArray()
array.clear()
`
Example with objects and custom compare function
`javascript
import BinarySortedArray from 'binary-sorted-array'
let compare = (a, b) => {
if (a.start === b.start) return 0
return a.start < b.start ? -1 : 1
}
let array = new BinarySortedArray([
{ id: 1, start: 1.123, title: 'some item'},
{ id: 2, start: 5, title: 'another item'},
{ id: 3, start: 6.89, title: 'yet another item'},
{ id: 4, start: 3.99 },
{ id: 5, start: 5 },
{ id: 6, start: 1.121 },
], comparator)
array.insert({ start: 0.99 })
array.remove({ id: 4, start: 3.99 })
array.indexOf({ start: 5 })
array.slice(2, 4)
let sortedArray = array.getArray()
array.clear()
`
$3
#### new BinarySortedArray(arr: Array, compare: function) ####
Constructor takes 2 parameters and if given array is not empty sorts the array during initialization.
Parameter
Description
Default value
arr
Array of items
[]
compare
Function comparing array items. Check default value for example
(a, b) => {
if (a === b) return 0
return a < b ? -1 : 1
}
#### .getArray() ####
Returns copy of sorted array
#### .insert(item) ####
Adds a new item to the array in the proper position
#### .indexOf(item, returnPossiblePlace) ####
Returns index of the item or -1 if it doesn't exist in the array. If returnPossiblePlace is set to true instead of -1 it returns a place in the array where the item could be placed (watch out - you don't know if the item is in the array in this case!)
#### .slice(start, end) ####
Performs slice operation on internal array and returns the result
#### .remove(item) ####
Removes first found item for which compare function (see constructor) returns 0
#### .clear()` ####