Created
April 25, 2017 19:32
-
-
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.
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
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