Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use Maps to only iterate through slices that actually have a given action #2

Merged
merged 4 commits into from
Apr 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,26 +91,28 @@ export function withSlices<Configs extends SliceConfig<string, unknown, any>[]>(
) => void,
) => {
const state: any = {};
const actionNameSet = new Set<string>();
const sliceMapsByAction = new Map<string, Map<string, any>>();
for (const config of configs) {
state[config.name] = config.value;
for (const actionName of Object.keys(config.actions)) {
actionNameSet.add(actionName);
for (const [actionName, actionFn] of Object.entries(config.actions)) {
let actionsBySlice = sliceMapsByAction.get(actionName);
if (!actionsBySlice) {
sliceMapsByAction.set(actionName, (actionsBySlice = new Map()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I like this syntax. I think I used two statements before for this pattern.

}
actionsBySlice.set(config.name, actionFn);
}
}
for (const actionName of actionNameSet) {
for (const [actionName, actionsBySlice] of sliceMapsByAction) {
state[actionName] = (...args: any[]) => {
// FIXME not very efficient to do this every time
for (const config of configs) {
const actionFn = config.actions[actionName];
if (actionFn) {
set((prevState: any) => {
const prevSlice = prevState[config.name];
const nextSlice = actionFn(...args)(prevSlice);
return { [config.name]: nextSlice } as any;
});
set((prevState: any) => {
const nextState: any = {};
for (const [sliceName, actionFn] of actionsBySlice) {
const prevSlice = prevState[sliceName];
const nextSlice = actionFn(...args)(prevSlice);
nextState[sliceName] = nextSlice;
}
}
return nextState;
});
};
}
return state;
Expand Down
Loading