Created
January 22, 2019 13:41
-
-
Save silicakes/4ce4dab4e8a2982eab3c8552147adbf4 to your computer and use it in GitHub Desktop.
clojure style threading macro example in js
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
// Threading macros, also known as arrow macros, | |
// convert nested function calls into a linear flow of function calls, | |
// improving readability. The idea is similar to 'pipelining' | |
const double = str => `${str} ${str}`; | |
const reverse = str => str.split("").reverse().join(''); | |
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1); | |
const pad = (maxLength, chr = ' ') => str => str.toString().padEnd(maxLength, chr); | |
const thread = function thread(...args) { | |
return args.reduce((val, fn) => fn(val), this); | |
} | |
// Option A: Binding it to the Object constructor | |
Object.prototype['->'] = thread; | |
// Option B: creating a more 'clojuresque' variation | |
globalThis['->'] = (value, ...args) => thread.apply(value, args); | |
// EXAMPLE USAGE | |
const str = 'carrot'; | |
// Option A: | |
str['->'](capitalize, | |
reverse, | |
double, | |
pad(20, 'Q')); //"torraCQQQQQQQQQQQQQQ torraCQQQQQQQQQQQQQQ" | |
// Option B: | |
globalThis['->'](str, | |
capitalize, | |
reverse, | |
double, | |
pad(20, 'Q')); //"torraCQQQQQQQQQQQQQQ torraCQQQQQQQQQQQQQQ" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment