Created
January 23, 2022 10:29
-
-
Save yornaath/a6e5a3a4a2c3cf13ee73631f99bd89ab to your computer and use it in GitHub Desktop.
This file contains hidden or 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 type Normalized<T extends Record<string | number | symbol, any>, K extends keyof T> = { | |
ids: T[K][], | |
byId: Partial<Record<T[K], T>> | |
} | |
export const fromArray = <T extends Record<string, any>, K extends keyof T> (array: T[], key: K): Normalized<T, K> => { | |
const keys = array.map(item => item[key]) | |
const index = array.reduce<Normalized<T, K>['byId']>((index, item) => { | |
return { | |
...index, | |
[`${item[key]}`]: item | |
} | |
}, {} as any) | |
return { ids: keys, byId: index } | |
} | |
export const toArray = <T extends Record<string, any>, K extends keyof T> (data: Normalized<T, K>): T[] => | |
Object.values(data.byId) | |
export const mergeR = <T extends Record<string, any>, K extends keyof T> (dataA: Normalized<T, K>, dataB: Normalized<T, K>): Normalized<T, K> => { | |
return { | |
ids: [...new Set([...dataA.ids, ...dataB.ids])], | |
byId: { | |
...dataA.byId, | |
...dataB.byId | |
} | |
} | |
} | |
export const mergeL = <T extends Record<string, any>, K extends keyof T> (dataA: Normalized<T, K>, dataB: Normalized<T, K>): Normalized<T, K> => { | |
return { | |
ids: [...new Set([...dataB.ids, ...dataA.ids])], | |
byId: { | |
...dataB.byId, | |
...dataA.byId | |
} | |
} | |
} | |
export const remove = <T extends Record<string, any>, K extends keyof T> (data: Normalized<T, K>, removeId: T[K] | (T[K])[]): Normalized<T, K> => { | |
const newIds = data.ids.filter(id => ( | |
Array.isArray(removeId) ? | |
removeId.indexOf(id) === -1 | |
: | |
id !== removeId | |
)) | |
return { | |
ids: newIds, | |
byId: newIds.reduce<Partial<{ | |
[K in keyof T]: T | |
}>>((byId, id) => ({ ...byId, [id]: data.byId[id] }), {}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment