Created
January 16, 2024 20:47
-
-
Save ezheidtmann/99d6899492d005cd59746838fd7b0938 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const keyComparator = <ItemT extends object, ComparableT extends number>( | |
keyTransform: (item: ItemT) => ComparableT | |
) => { | |
const _cache = new WeakMap<ItemT, ComparableT>(); | |
const cachedTransform = (item: ItemT) => { | |
if (!_cache.has(item)) { | |
_cache.set(item, keyTransform(item)); | |
} | |
return _cache.get(item) as ComparableT; | |
}; | |
return (a: ItemT, b: ItemT) => cachedTransform(a) - cachedTransform(b); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment