Skip to content

Instantly share code, notes, and snippets.

@artalar
Created July 20, 2019 16:57
Show Gist options
  • Select an option

  • Save artalar/858fff1c4f3568a362dee699635a6736 to your computer and use it in GitHub Desktop.

Select an option

Save artalar/858fff1c4f3568a362dee699635a6736 to your computer and use it in GitHub Desktop.
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