@philiprehberger/sorted-array
v0.2.0
Published
Sorted array with binary search — maintains order on insert
Readme
@philiprehberger/sorted-array
Sorted array with binary search — maintains order on insert.
Installation
npm install @philiprehberger/sorted-arrayUsage
import { sortedArray } from '@philiprehberger/sorted-array';
const arr = sortedArray<number>();
arr.insert(5);
arr.insert(1);
arr.insert(3);
console.log(arr.toArray()); // [1, 3, 5]
console.log(arr.has(3)); // true
console.log(arr.range(1, 4)); // [1, 3]
// Custom comparator (descending)
const desc = sortedArray<number>((a, b) => b - a);
desc.insert(1);
desc.insert(3);
desc.insert(2);
console.log(desc.toArray()); // [3, 2, 1]Reverse Iteration
const arr = sortedArray<number>();
[3, 1, 5, 2, 4].forEach((n) => arr.insert(n));
for (const value of arr.reversed()) {
console.log(value); // 5, 4, 3, 2, 1
}Closest Value Lookup
const arr = sortedArray<number>();
[1, 5, 10, 20].forEach((n) => arr.insert(n));
console.log(arr.closest(6)); // 5
console.log(arr.closest(15)); // 10
console.log(arr.closest(25)); // 20Statistical Methods
const arr = sortedArray<number>();
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((n) => arr.insert(n));
console.log(arr.sum()); // 55
console.log(arr.median()); // 5.5
console.log(arr.percentile(90)); // 9Unique Filter
const arr = sortedArray<number>();
[1, 2, 2, 3, 3, 3].forEach((n) => arr.insert(n));
const uniq = arr.unique();
console.log(uniq.toArray()); // [1, 2, 3]API
sortedArray<T>(comparator?)
Creates a new sorted array. Accepts an optional comparator function.
Returns a SortedArray<T> with:
insert(value)— Insert a value in sorted positionremove(value)— Remove a value, returnstrueif foundhas(value)— Check if a value existsindexOf(value)— Get index of value, or-1range(min, max)— Get all values between min and max (inclusive)toArray()— Get a copy of the internal arrayreversed()— Return an iterable for descending traversalclosest(value)— Find the nearest element using binary searchunique()— Return a newSortedArraywith duplicates removedmedian()— Median value (averages middle two for even-length arrays)percentile(p)— Value at the given percentile (0-100)sum()— Sum of all elements (numeric arrays)length— Number of elementsfirst— First (smallest) element orundefinedlast— Last (largest) element orundefined[Symbol.iterator]()— Iterate in sorted order
Development
npm install
npm run build
npm testSupport
If you find this project useful:
