Created
March 2, 2016 17:33
-
-
Save panuhorsmalahti/6b3914df571a7b7879d4 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
// copied from https://gist.github.com/lauripiispanen/1fd1c3319084f9913f2d | |
// improved formatting | |
const constrain = ({ | |
pre = () => {}, | |
post = () => {} | |
}) => fn => (...args) => { | |
const throwIf = x => y => { | |
if (x(y)) { | |
throw x(y); | |
} else { | |
return y; | |
} | |
}; | |
const compose = (...args) => args.reduce((x,f n) => (...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