Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active October 18, 2017 04:07
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 mattpodwysocki/afdb9c6126b7f3a61ac4053570af4099 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/afdb9c6126b7f3a61ac4053570af4099 to your computer and use it in GitHub Desktop.
import { AsyncIterableX } from '../asynciterable';
import { AsyncSink } from '../asyncsink';
import { memoize } from './memoize';
export function bindCallback<TSource>(
func: Function,
selector: Function
): (...args: any[]) => AsyncIterableX<TSource> {
return function(...args: any[]) {
const sink = new AsyncSink<TSource>();
const handler = function(...innerArgs: any[]) {
if (selector) {
try {
const result = selector(...innerArgs);
sink.write(result);
} catch (e) {
sink.error(e);
}
} else {
sink.write(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
}
};
try {
func.apply(null, args.concat(handler));
} catch (e) {
sink.error(e);
}
return memoize(
(async function*() {
for (let next; !(next = await sink.next()).done; ) {
yield next.value;
}
sink.end();
})()
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment