Last active
March 3, 2016 09:18
-
-
Save lauripiispanen/1fd1c3319084f9913f2d to your computer and use it in GitHub Desktop.
Clojure-style :pre and :post constraints in ES6 - big thanks to @polytypic for the original idea!
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
const constrain = ({ pre = () => {}, post = () => {} }) => fn => (...args) => { | |
const throwIf = x => y => { if (x(y)) { throw x(y) } else return y }, | |
compose = (...args) => args.reduce((x,fn) => (...args) => fn(x.apply(x, args))) | |
return compose(throwIf(pre), fn.bind(fn, args), throwIf((...a) => post.apply(a.concat(args)))).apply(null, args) | |
} | |
const sqrt = constrain( | |
{pre: x => x < 0 && "Let's go shopping!", | |
post: (y, x) => y < 0 && "Math is hard." | |
|| 0.1 < y*y - x && "Floats are harder.", | |
doc: "Round root"})(Math.sqrt) | |
console.log(sqrt(9)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment