@idealic/poker-engine
Version:
Professional poker game engine and hand evaluator with built-in iterator utilities
51 lines • 2.14 kB
JavaScript
import { pubsub } from './lib/pubsub';
import { writer } from './lib/writer';
/**
* Partition function takes a splitter function and multiple processors.
* The splitter function splits each input item into a tuple of parts.
* Items returned from splitter get routed to processors by index
*
* Backpressure is provided both by downstream steps and by branching steps.
*
* @param splitter Function that splits each input item into a tuple
* @param processors Processing functions, one for each position in the tuple
* @returns A function that takes an iterable input and returns processed results
*/
export function _dispatch(iterator, splitter, branches, concurrency = 1) {
const writers = Object.entries(branches).reduce((acc, [key, branch]) => {
return { ...acc, [key]: writer(branch, concurrency) };
}, {});
const { output, input, onReadError, onReadComplete } = pubsub(concurrency);
var isDone = false;
const dispatcher = async (item, index, iterable) => {
const branched = await splitter(item);
await Promise.all(Object.entries(branched).map(([key, value]) => value === undefined ? undefined : writers[key]?.write(value)));
// yield item back to allow downstream to control the consumption
return item;
};
let streams = [];
return output({
onStart: async () => {
streams = Object.values(writers).map(writer => writer.start());
input(iterator, dispatcher);
Promise.all(streams).catch(e => {
onReadError(e);
onReadComplete();
});
},
onComplete: async () => {
await Promise.all(Object.values(writers).map(writer => writer.end()));
// allow streams to throw errors
await Promise.all(streams);
},
});
}
export function dispatch(input, splitter, branches, concurrency) {
if (typeof input === 'function') {
return (_input) => dispatch(_input, input, splitter, branches);
}
else {
return _dispatch(input, splitter, branches, concurrency);
}
}
//# sourceMappingURL=dispatch.js.map