Created
July 20, 2019 16:57
-
-
Save artalar/858fff1c4f3568a362dee699635a6736 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
| function createMapById<PropName extends string>( | |
| $list: Store<{ [key in PropName]: any }[]>, | |
| propName: PropName, | |
| id: string | |
| ) { | |
| return $list.map(list => | |
| list.reduce( | |
| (propByIdMap, element) => ( | |
| (propByIdMap[element[id]] = element[propName]), propByIdMap | |
| ), | |
| {} | |
| ) | |
| ); | |
| } | |
| export function createList(propsList: string[], uidPropName: string) { | |
| const $list = createStore([]); | |
| const $listNorm = propsList.reduce( | |
| (propsMap, propName) => ( | |
| (propsMap[propName] = createMapById($list, propName, uidPropName)), | |
| propsMap | |
| ), | |
| {} | |
| ); | |
| function createListElement(id: string) { | |
| return combine(propsList.reduce( | |
| (elementShape, propName) => ( | |
| (elementShape[propName] = $listNorm[propName].map(propByIdMap => propByIdMap[id]), | |
| elementShape | |
| )), | |
| {} | |
| )); | |
| } | |
| $list.createListElement = createListElement | |
| return $list | |
| } | |
| // USAGE | |
| const $users = createList(['id', 'email', 'name'], 'id') | |
| .on(fetchUsers.done, (_, payload) => payload) | |
| fetchUsers.done([{ id: 1, email: 'a@b.c', name: 'name' }]) | |
| const $firstUser = $users.createListElement(1) | |
| $firstUser.getState() | |
| // { id: 1, email: 'a@b.c', name: 'name' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment