Last active
July 4, 2016 16:08
-
-
Save renaudtertrais/07400a882ebe2cd1f442a7d5f2e564b7 to your computer and use it in GitHub Desktop.
A simple ES6 bind function to implement Railway oriented programming. https://vimeo.com/113707214
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 compose = (...fns) => (...args) => { | |
return fns.slice(0, -1).reduceRight((res, fn) => fn(res), | |
fns[fns.length -1].apply(null,args) | |
); | |
}; | |
const bind = (f) => (...args) => { | |
if(args[0] instanceof Error) return args[0]; | |
try{ | |
return f.apply(null, args); | |
}catch(e){ | |
if(e instanceof Error) return e; | |
return new Error(e); | |
} | |
}; | |
class Error{ | |
constructor(err){ | |
this.error = err; | |
} | |
} | |
// stupid example | |
const isDivisible = (d) => (n) => { | |
if(n % d) throw `${n} is not divisible by ${d}`; | |
return n; | |
} | |
const isDivisibleBy3 = isDivisible(3); | |
const isDivisibleBy4 = isDivisible(4); | |
const isDivisibleBy6 = isDivisible(6); | |
const isDivisibleBy3And4And6 = compose( | |
bind((n) => `${n} is divisible by 3, 4 and 6`), | |
bind(isDivisibleBy6), | |
bind(isDivisibleBy4), | |
bind(isDivisibleBy3) | |
) | |
isDivisibleBy3And4And6(4); // { error: "4 is not divisible by 6" } | |
isDivisibleBy3And4And6(6); // { error: "6 is not divisible by 4" } | |
isDivisibleBy3And4And6(12); // "12 is divisible by 3, 4 and 6" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment