Last active
February 25, 2020 20:53
-
-
Save cowboy/0786fa1f8ebf58991d34 to your computer and use it in GitHub Desktop.
WIP: ES2015 heredoc helper
This file contains hidden or 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
function chainOptions(props, fn) { | |
function getWrapper(options = {}) { | |
const wrapper = (...args) => fn(options, ...args); | |
props.forEach(prop => { | |
Object.defineProperty(wrapper, prop, { | |
enumerable: true, | |
get() { | |
return getWrapper(Object.assign({}, options, {[prop]: !options[prop]})); | |
}, | |
set() {}, | |
}); | |
wrapper[prop] = (...args) => wrapper(...args); | |
}); | |
return wrapper; | |
} | |
return getWrapper(); | |
} | |
function templateTagDefault(strings, ...values) { | |
return strings.reduce((result, string, n) => result + (n > 0 ? values[n - 1] : '') + string, ''); | |
} | |
const heredoc = chainOptions(['trim', 'unindent', 'oneline'], function({trim, unindent, oneline}, ...args) { | |
let s = templateTagDefault(...args); | |
let lines = s.split('\n'); | |
if (unindent) { | |
// Convert any only-whitespace lines to '' | |
lines = lines.map(s => /\S/.test(s) ? s : ''); | |
// Unindent every line by the minimum indent shared by all non-whitespace lines. | |
const indent = lines.filter(Boolean).reduce( | |
(n, s) => Math.min(n, s.match(/^\s*/)[0].length), Infinity); | |
lines = lines.map(s => s.slice(indent)); | |
// Remove any leading/trailing whitespace lines. | |
s = lines.join('\n'); | |
if (trim) { | |
s = s.replace(/^\n+|\n+$/g, ''); | |
} | |
} | |
else if (oneline) { | |
if (trim) { | |
lines = lines.map(s => s.replace(/^\s+|\s+$/g, '\uFFFF')); | |
s = lines.join('\uFFFF'); | |
s = s.replace(/\uFFFF+/g, ' ').replace(/^\s+|\s+$/g, ''); | |
} | |
else { | |
s = s.replace(/\n+/g, ''); | |
} | |
} | |
else if (trim) { | |
s = s.replace(/^\s+|\s+$/g, ''); | |
} | |
return s; | |
}); |
This file contains hidden or 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
Before text. | |
array has length=3 and items=a-b-c | |
test | |
1 2 3 | |
After text. |
This file contains hidden or 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 a = ["a", "b", "c"]; | |
const foo = heredoc.unindent.trim` | |
Before text. | |
array has length=${a.length} and items=${a.join("-")} | |
test | |
1 2 3 | |
After text. | |
`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Done. https://github.com/cowboy/node-heredoc-tag