Sorted array with binary search — maintains order on insert
npm install @philiprehberger/sorted-arraySorted array with binary search — maintains order on insert.
npm install @philiprehberger/sorted-array
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]
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
}
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)); // 20
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)); // 9
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]
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, returns true if 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 new SortedArray with 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 or undefinedlast — Last (largest) element or undefined[Symbol.iterator]() — Iterate in sorted ordernpm install
npm run build
npm test
If you find this project useful: