From 077a7571c7eddf79236417e789bcc51357f4011b Mon Sep 17 00:00:00 2001 From: Ben Durrant Date: Sun, 21 Apr 2024 02:52:42 +0100 Subject: [PATCH] use Maps to only iterate through slices that actually have a given action (#2) * use Maps to only iterate through slices that actually have a matching action * use Object.entries instead of Object.keys * only call set once per action --------- Co-authored-by: Daishi Kato --- src/index.ts | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/index.ts b/src/index.ts index 4e53bcc..f5fbf1b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -91,26 +91,28 @@ export function withSlices[]>( ) => void, ) => { const state: any = {}; - const actionNameSet = new Set(); + const sliceMapsByAction = new Map>(); 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())); + } + 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;