From db5b68592c9418f63ef393b00cce561d69276cf7 Mon Sep 17 00:00:00 2001 From: Matei Adriel <rafaeladriel11@gmail.com> Date: Fri, 24 Apr 2020 17:03:32 +0300 Subject: [PATCH] typescript(monadic): refactor: moved the component stuff in a new file Signed-off-by: prescientmoon <git@moonythm.dev> --- typescript/monadic/src/component.ts | 25 +++++++++++++++++++++++++ typescript/monadic/src/environment.ts | 26 +------------------------- 2 files changed, 26 insertions(+), 25 deletions(-) create mode 100644 typescript/monadic/src/component.ts diff --git a/typescript/monadic/src/component.ts b/typescript/monadic/src/component.ts new file mode 100644 index 0000000..d0fa2f3 --- /dev/null +++ b/typescript/monadic/src/component.ts @@ -0,0 +1,25 @@ +import { IterableEmitter } from './iterableEmitter'; + +export type Component<T, S, A> = { + render: (state: S, dispatch: (a: A) => () => void) => T; + handleActions: (action: A, state: S) => S; +}; + +export async function* runComponent<T, S, A>( + component: Component<T, S, A>, + initialState: S +): AsyncGenerator<T> { + const emitter = new IterableEmitter(initialState); + + const dispatch = (state: S) => (action: A) => { + const newState = component.handleActions(action, state); + + return () => { + emitter.next(newState); + }; + }; + + for await (const state of emitter) { + yield component.render(state, dispatch(state)); + } +} diff --git a/typescript/monadic/src/environment.ts b/typescript/monadic/src/environment.ts index 2a1bf14..0701917 100644 --- a/typescript/monadic/src/environment.ts +++ b/typescript/monadic/src/environment.ts @@ -1,4 +1,4 @@ -import { IterableEmitter } from './iterableEmitter'; +import { Component, runComponent } from './component'; export type EnvConfig<T, S, A> = { render: (template: T, parent: HTMLElement) => void; @@ -7,30 +7,6 @@ export type EnvConfig<T, S, A> = { initialState: S; }; -export type Component<T, S, A> = { - render: (state: S, dispatch: (a: A) => () => void) => T; - handleActions: (action: A, state: S) => S; -}; - -async function* runComponent<T, S, A>( - component: Component<T, S, A>, - initialState: S -): AsyncGenerator<T> { - const emitter = new IterableEmitter(initialState); - - const dispatch = (state: S) => (action: A) => { - const newState = component.handleActions(action, state); - - return () => { - emitter.next(newState); - }; - }; - - for await (const state of emitter) { - yield component.render(state, dispatch(state)); - } -} - export const runUi = async <T, S, A>( config: EnvConfig<T, S, A> ): Promise<void> => {