Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
makeReduxStrategy
import makeReduxStrategy, {ReduxAction, ReduxReducer} from './makeReduxAction';
interface CounterAction extends ReduxAction {
payload: number;
}
const counterStrategy = makeReduxStrategy<number>({
ADD: (state: number, {payload}: CounterAction) => state + payload,
SUBTRACT: (state: number, {payload}: CounterAction) => state - payload,
})
const sampleCounter: ReduxReducer<number> = (state, action: CounterAction) => counterStrategy[action.type](state, action);
const a = sampleCounter(5, {type: "ADD", payload: 3}); // 8
const b = sampleCounter(a, { type: "SUBTRACT", payload: 13 }); // -5
const c = sampleCounter(b, { type: "FOO", payload: 20000 }); // does nothing, -5;
// transpiled
const withDefault = (target, defaultResponse) => {
if (!target.__default__ && !defaultResponse) {
throw new Error(`No default function provided for withDefault`);
}
return new Proxy(target, {
get: (t, k) => {
if (k in t) {
return t[k];
}
if (!!t.__default__) {
return t.__default__;
}
return defaultResponse;
}
});
};
const makeReduxStrategy = (reducerMap) => withDefault(reducerMap, (state, _unusedAction) => state);
export default makeReduxStrategy;
const withDefault = <T>(
target: Record<string, T>,
defaultResponse?: any
): ProxyHandler<Record<string, T>> => {
if (!target.__default__ && !defaultResponse) {
throw new Error(`No default function provided for withDefault`);
}
return new Proxy(target, {
get: (t: Record<string, T>, k: string) => {
if (k in t) {
return t[k];
}
if (!!t.__default__) {
return t.__default__;
}
return defaultResponse;
}
});
};
export type ReduxAction = {
type: string;
[k: string]: any;
};
export type ReduxReducer<S> = (state: S, action?: ReduxAction) => S;
const makeReduxStrategy = <S>(reducerMap: Record<string, ReduxReducer<S>>) =>
withDefault<ReduxReducer<S>>(
reducerMap,
(state: S, _unusedAction?: ReduxAction): S => state
);
export default makeReduxStrategy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.