Binary Sorted Array
An array sorted using binary search algorithm. Binary search is used when calling indexOf
or insert
(to find position in the array where the item should be inserted).
Installation
There are 2 options:
- Download
lib/index.js
file - use npm
npm i --save binary-sorted-array
Usage
Basic usage example
let array = 1 5 6 3 5 1arrayarrayarraylet sortedArray = arrayarrayclear
Example with objects and custom compare function
let { if astart === bstart return 0 return astart < bstart ? -1 : 1}let array = id: 1 start: 1123 title: 'some item' id: 2 start: 5 title: 'another item' id: 3 start: 689 title: 'yet another item' id: 4 start: 399 id: 5 start: 5 id: 6 start: 1121 comparatorarrayarrayarrayarraylet sortedArray = arrayarrayclear
Documentation
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()
Clears the array