Skip to content

Instantly share code, notes, and snippets.

@m-wiley
Created August 23, 2019 17:01
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 m-wiley/2c901af7193c84bd3c424dc38c90e748 to your computer and use it in GitHub Desktop.
Save m-wiley/2c901af7193c84bd3c424dc38c90e748 to your computer and use it in GitHub Desktop.
import { IHashMap } from '@shared/models';
import * as _ from 'lodash';
export class HashMap<T> {
private key: string;
private keys: Array<string>;
private hashMap: IHashMap<T> = {};
public length: number;
constructor(input: IHashMap<T> | Array<T> = {}, key = 'id') {
if (input instanceof Array) {
this.key = key;
this.hashMap = _.keyBy(input, key);
this.length = input.length;
} else {
this.key = key;
this.hashMap = input;
this.length = Object.keys(input).length;
}
this.keys = Object.keys(this.hashMap);
}
find(callback: (item: T) => boolean): T {
for (const key in this.hashMap) {
if (callback(this.hashMap[key])) {
return this.hashMap[key];
}
}
return undefined;
}
map(callback: (item: T) => any): Array<any> {
return Object.values(this.hashMap).map(callback);
}
filter(callback: (item: T) => boolean): HashMap<T> {
const filteredValuesArray = Object.values(this.hashMap).filter(callback);
const filteredValuesMap = Object.assign(
{},
...filteredValuesArray.map(item => ({
[item[this.key]]: item
}))
);
return new HashMap<T>(filteredValuesMap, this.key);
}
immutableUpdate(key: string | number, item: Partial<T>): HashMap<T> {
return new HashMap<T>({
...this.hashMap,
[key]: {
...this.hashMap[key],
...item
}
}, this.key);
}
immutableMerge(hashMap: HashMap<T>): HashMap<T> {
return new HashMap<T>({
...this.hashMap,
...hashMap.hashMap
}, this.key);
}
itemAt(index: number): T {
return this.hashMap[this.keys[index]];
}
*[Symbol.iterator](): Iterator<T> {
for (const hashItem of Object.values(this.hashMap)) {
yield hashItem;
}
}
valueOf() {
return this.hashMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment