Last active
October 18, 2017 04:07
-
-
Save mattpodwysocki/afdb9c6126b7f3a61ac4053570af4099 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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