Skip to content

Instantly share code, notes, and snippets.

@coding-lemur
Created October 17, 2020 14:43
Show Gist options
  • Select an option

  • Save coding-lemur/90e666b928f692b2ab516f4fda2594d4 to your computer and use it in GitHub Desktop.

Select an option

Save coding-lemur/90e666b928f692b2ab516f4fda2594d4 to your computer and use it in GitHub Desktop.
Helper functions to work dictionaries on #angular #ngrx
export interface HasId {
id: string;
}
export interface HasOrderIndex {
orderIndex: number;
}
export interface Dictionary<T extends HasId> {
[id: string]: T;
}
export class StoreHelper {
static dictToArray<T extends HasId & HasOrderIndex>(
dict: Dictionary<T>
): Array<T> {
if (dict == null) {
return [];
}
const keys = this.getKeys(dict);
if (keys.length === 0) {
return [];
}
const list = keys.map((key) => dict[key]);
const firstKey = keys[0];
const firstItem = dict[firstKey];
if (firstItem.orderIndex == null) {
return list;
}
// sort list by orderIndex
const sortedList = list.sort((a, b) => {
if (a.orderIndex < b.orderIndex) {
return -1;
}
if (a.orderIndex > b.orderIndex) {
return 1;
}
return 0;
});
return sortedList;
}
static arrayToDict<T extends HasId & HasOrderIndex>(
items: T[],
initValues = {}
): Dictionary<T> {
if (items == null) {
return {};
}
// TODO add autogenerated orderIndex for each item
return items.reduce(
(prevValue: Dictionary<T>, item: T) => {
return {
...prevValue,
[item.id]: item,
};
},
{ ...initValues }
);
}
static getKeys<T extends HasId>(dict: Dictionary<T>): string[] {
const keys = Object.keys(dict);
return keys;
}
static getDictCount<T extends HasId>(dict: Dictionary<T>): number {
if (dict == null) {
return 0;
}
const keys = this.getKeys(dict);
return keys.length;
}
static getIndexByDictKey<T extends HasId>(
dict: Dictionary<T>,
key: string
): number {
const keys = this.getKeys(dict);
const index = keys.indexOf(key);
return index;
}
static removeKey<T extends HasId>(
dict: Dictionary<T>,
deleteKey: number
): Dictionary<T> {
if (dict == null) {
return;
}
if (!(deleteKey in dict)) {
return dict;
}
// ES7 magic: destructuring assignment to remove keys from dict
const { [deleteKey]: deletedItem, ...newDict } = dict;
return newDict;
}
static removeKeys<T extends HasId>(
dict: Dictionary<T>,
deleteKeys: number[]
): Dictionary<T> {
if (dict == null) {
return;
}
let newDict: Dictionary<T> = { ...dict };
if (deleteKeys == null || deleteKeys.length === 0) {
return newDict;
}
for (const key of deleteKeys) {
newDict = this.removeKey(newDict, key);
}
return newDict;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment