The type of values stored in the map
Finds the key-value pair with the largest key that is less than or equal to the target.
This method uses binary search to efficiently locate the closest match. If no key is less than or equal to the target, it returns undefined.
Time complexity: O(log n)
The number to search for
The key-value pair with the largest key ≤ target, or undefined if none exists
const map = new SortedNumberMap<string>();
map.set(10, 'ten');
map.set(20, 'twenty');
map.set(30, 'thirty');
// Exact match
map.findClosestLessThanOrEqual(20); // { key: 20, value: 'twenty' }
// Closest less than
map.findClosestLessThanOrEqual(25); // { key: 20, value: 'twenty' }
// No match (target too small)
map.findClosestLessThanOrEqual(5); // undefined
Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
Time complexity: O(1)
Returns the element associated with the specified key. If no element is associated
with the specified key, returns undefined.
TSDoc adapted from Map.get
Returns an iterable of keys in the map sorted in ascending order.
Time complexity: internal detail to JavaScript engine. Reasonable expectation:
Note that iterating over the keys this way negates the benefits of using this class over a using a Map. To access individual keys more quickly, use SortedNumberMap.findClosestLessThanOrEqual or SortedNumberMap.get.
TSDoc adapted from Map.keys
Sets a key-value pair in the map. If the key already exists, its value is updated. If the key is new, it's inserted in the correct sorted position.
Time complexity: O(log n) for new keys (due to binary search and array insertion), O(1) for existing keys.
The numeric key to set
The value to associate with the key
A map-like data structure that maintains numeric keys in sorted order and provides efficient operations for finding the closest key-value pair less than or equal to a target.
This class combines the benefits of a Map (O(1) key-value lookups) with sorted key access (O(log n) binary search operations). It's particularly useful when you need to frequently find the "closest" entry to a given numeric key.
Example