Skip to content

Instantly share code, notes, and snippets.

@nmn
Created April 25, 2017 19:32
Show Gist options
  • Save nmn/2d99855eaaac0906f31e4a16a3109c67 to your computer and use it in GitHub Desktop.
Save nmn/2d99855eaaac0906f31e4a16a3109c67 to your computer and use it in GitHub Desktop.
a higher-order-function that almost maintains the function signature, but not quite.
type ITask<I: $ReadOnlyArray<mixed>, O> = {
(...r: I): ?O,
lastError?: Error
}
function task <I: $ReadOnlyArray<mixed>, O>(inner: (...r: I) => O): ITask<I, O> {
const wrapped: any = function wrapped() {
try {
return (inner: any).apply(this, arguments)
} catch (err) {
(wrapped:any).lastError = err
}
}
wrapped.lastError = null
return wrapped
}
const t = task((str: string) => str.length)
t('hello') // good
t(123) // error, good
t(true) // error, good
console.log(t.lastError) // good
console.log(t.haha) // error, good
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment