Created
January 31, 2018 13:06
-
-
Save renanpvaz/e0e55082fa1d4a642eb7d1b1cc463010 to your computer and use it in GitHub Desktop.
experimental higher-order contract function
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
signatureToTypes = sig => sig | |
.split(' -> ') | |
.map(type => ({ | |
Number: { | |
ctor: Number, | |
type: 'number', | |
}, | |
Object: { | |
ctor: Object, | |
type: 'object', | |
}, | |
String: { | |
ctor: String, | |
type: 'string', | |
}, | |
})[type]) | |
throwError = msg => { | |
throw new Error(msg) | |
} | |
contract = (sig, f) => { | |
const types = signatureToTypes(sig) | |
return (...args) => | |
types.every(({ ctor, type }, i) => args[i] instanceof ctor || typeof args[i] === type) | |
? f(...args) | |
: throwError(`Contract broke, expected types were: ${types.map(t => t.ctor.name)}`) | |
} | |
add = contract('Number -> Number', | |
(a, b) => a + b | |
) | |
/* | |
@contract('Number -> Number') | |
add = (a, b) => a + b | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment