Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created July 4, 2021 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fostyfost/ce60969e211f1859d3997af1aa7e64f2 to your computer and use it in GitHub Desktop.
Save fostyfost/ce60969e211f1859d3997af1aa7e64f2 to your computer and use it in GitHub Desktop.
comparable-map.ts
export interface ComparableMap<K = string, V = unknown> {
keys: K[]
get(key: K): V | undefined
add(key: K, value: V): void
remove(key: K): V | undefined
}
/**
* We will use it where we can not use the default Map as the Map class do not allow custom compare function.
*
* @param equalityCheck Optional, a comparer to use
*/
export const getComparableMap = <K = string, V = unknown>(
equalityCheck: (left: K, right: K) => boolean,
): ComparableMap<K, V> => {
const keys: K[] = []
const values: { [key: number]: V } = {}
return {
/**
* Current set of keys.
*/
keys,
/**
* Gets value for given key.
*
* @param key
*/
get(key: K): V | undefined {
const index = keys.findIndex(currentKey => equalityCheck(currentKey, key))
if (index === -1) {
return undefined
}
return values[index]
},
/**
* Adds the given key and value.
*
* @param key
* @param value
*/
add(key: K, value: V) {
const index = keys.findIndex(currentKey => equalityCheck(currentKey, key))
if (index === -1) {
keys.push(key)
values[keys.length - 1] = value
}
},
/**
* Removes the given key and returns the value object if key was found.
*
* @param key
*/
remove(key: K): V | undefined {
const index = keys.findIndex(currentKey => equalityCheck(currentKey, key))
if (index === -1) {
return undefined
}
delete keys[index]
const value = values[index]
delete values[index]
return value
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment