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

better subscription configuration #3

Merged
merged 1 commit into from Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/effects/index.ts
@@ -1,6 +1,5 @@
import { type State, createHandler, subscribe } from "../state";
import { skipDuplicates, perTick } from "../transformers";
import { pull, compose } from "../util";
import { ensureConnection, removeWsListeners } from "./ensureConnection";
import { type Effect } from "./types";

Expand All @@ -13,9 +12,7 @@ const setState = createHandler((_oldState, newState: State) => newState);

const effects: Effect[] = [ensureConnection, removeWsListeners];

const subscribeEffects = pull(
compose(skipDuplicates<State>(), perTick<State>())
)(subscribe);
const subscribeEffects = subscribe.with(skipDuplicates()).with(perTick());

subscribeEffects((state) => {
setState(effects.reduce((newState, effect) => effect(newState), state));
Expand Down
6 changes: 5 additions & 1 deletion src/state.ts
@@ -1,6 +1,7 @@
import { initState } from "./state-management";
import { type BrandString, BetterRecord } from "./type-util";
import { type RecordOf, List } from "immutable";
import { makeConfigurable } from "./util";

export const makePlayerStatus = BetterRecord<
PlayerStatusProps,
Expand Down Expand Up @@ -36,10 +37,13 @@ export const makeConnectingState = BetterRecord<ConnectingStateProps, "ws">({
ws: undefined,
});

export const { createHandler, subscribe, unsubscribe } = initState<State>(
const { createHandler, subscribe: baseSubscribe } = initState<State>(
makeDisconnectedState()
);

export { createHandler };
export const subscribe = makeConfigurable(baseSubscribe);

export type State = ConnectedState | DisconnectedState | ConnectingState;

type BaseStateProps = {
Expand Down
24 changes: 15 additions & 9 deletions src/util.ts
@@ -1,9 +1,15 @@
export const pull =
<A, B>(f: (a: A) => B) =>
<C>(g: (b: B) => C) =>
(a: A) =>
g(f(a));
export const compose =
<A, B, C>(g: (b: B) => C, f: (a: A) => B) =>
(a: A) =>
g(f(a));
type ConfigurableFunction<A, B> = {
with: <C>(transformer: (c: C) => A) => ConfigurableFunction<C, B>;
(a: A): B;
};

export const makeConfigurable = <A, B>(
f: (a: A) => B
): ConfigurableFunction<A, B> => Object.assign(f, { with: withProperty });

function withProperty<A, B, C>(
this: (a: A) => B,
transformer: (c: C) => A
): ConfigurableFunction<C, B> {
return makeConfigurable((c: C) => this(transformer(c)));
}