Skip to content

Instantly share code, notes, and snippets.

@lauripiispanen
Last active March 3, 2016 09:18
Show Gist options
  • Save lauripiispanen/1fd1c3319084f9913f2d to your computer and use it in GitHub Desktop.
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!
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