Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active February 25, 2020 20:53
Show Gist options
  • Save cowboy/0786fa1f8ebf58991d34 to your computer and use it in GitHub Desktop.
Save cowboy/0786fa1f8ebf58991d34 to your computer and use it in GitHub Desktop.
WIP: ES2015 heredoc helper
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;
});
Before text.
array has length=3 and items=a-b-c
test
1 2 3
After text.
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.
`;
@cowboy
Copy link
Author

cowboy commented Jan 22, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment