Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Last active March 7, 2016 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bouzuya/9452b24cf80fd74465cb to your computer and use it in GitHub Desktop.
Save bouzuya/9452b24cf80fd74465cb to your computer and use it in GitHub Desktop.
b-o-a をもっと簡素化できないか
// 1. Aciton の data を受けて次の Action type & data を返す関数群
// 2. 1 個の Action を N 個の ActionHandler で処理したい
// X 3. N 個の Action に共通の ActionHandler を追加したい
// -> merge, chain がほしい。dummy の Action を追加するのは辛い
// framework
import { EventEmitter } from 'events';
type NextAction = (action: Action) => void;
type ActionHandler = (data: any, re: NextAction) => Action;
type Action = {
type: string;
data: any;
}
type App = { [actionType: string]: ActionHandler | ActionHandler[] };
const run = (app: App): void => {
const emitter = new EventEmitter();
const re: NextAction = (action: Action) => setTimeout(() => emitter.emit(action));
emitter.on(action => {
const { type, data } = action;
const handler = app[type];
const hoh = app[type];
const handlers = Array.isArray(hoh) ? hoh : [hoh];
handlers.forEach(handler => {
re(handler(data, re));
});
});
};
// app
const action1: ActionHandler = (data, next) => {
// 3.NG
// oh...
// let result = action4(data, next); //...
return { type: 'action2', data: 123 };
};
const action2: ActionHandler = (data, next) => {
// 3.NG
// oh...
// let result = action4(data, next); //...
return null;
};
const action3: ActionHandler = (data, next) => {
console.log(data);
return null;
};
const action4: ActionHandler = (data, next) => {
console.log('action 4');
return null;
};
// 3. NG
// const app: App = {
// 'action1': [action1, action3, action4], // oh...
// 'action2': [action2, action4] // oh...
// };
const app: App = {
'action1': [action1, action3],
'action2': [action2]
};
run(app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment