Skip to content

Instantly share code, notes, and snippets.

@leonadler
Last active January 15, 2020 19:33
Show Gist options
  • Save leonadler/203bd34d46a0bc267726d9fc84c926c7 to your computer and use it in GitHub Desktop.
Save leonadler/203bd34d46a0bc267726d9fc84c926c7 to your computer and use it in GitHub Desktop.
Tagged template unindent helper
export function unindent(template: TemplateStringsArray, ...args: any[]): string {
let numSpaces = 999;
for (const part of template) {
for (const indentation of part.match(/\n +/g) || []) {
numSpaces = Math.min(numSpaces, indentation.length - 1);
}
}
const spaces = new RegExp('\n' + ' '.repeat(numSpaces < 999 ? numSpaces : 0), 'g');
return template
.map((part, i) => (i ? args[i - 1] : '') + part.replace(spaces, '\n'))
.join('')
.replace(/^\n|\n$/g, '');
}
import { unindent } from './unindent';
const a = unindent`
Helper to remove
indentation
from tagged text
`;
console.assert(a === 'Helper to remove\n indentation\nfrom tagged text', 'a');
const b = unindent`
The smallest
indentation is used
for all lines
`;
console.assert(b === ' The smallest\nindentation is used\n for all lines', 'b');
const c = unindent`
Variables
are inserted (${1 + 2})
as expected
`;
console.assert(c === 'Variables\n are inserted (3)\nas expected', 'c');
const d = unindent`
Extra leading or trailing
newlines are preserved
`;
console.assert(d === '\nExtra leading or trailing\nnewlines are preserved\n', 'd');
export function unindent(template, ...args) {
let numSpaces = 999;
for (const part of template) {
for (const indentation of part.match(/\n +/g) || []) {
numSpaces = Math.min(numSpaces, indentation.length - 1);
}
}
const spaces = ' '.repeat(numSpaces < 999 ? numSpaces : 0);
const spacesRegex = new RegExp('\n' + spaces, 'g');
return template
.map((part, i) => (i ? args[i - 1] : '') + part.replace(spacesRegex, '\n'))
.join('')
.replace(/^\n|\n$/g, '');
}
export function unindent(n,...e){let t=999;for(const e of n)for(const n of e.match(/\n +/g)||[])t=Math.min(t,n.length-1);const o=" ".repeat(t<999?t:0),r=new RegExp("\n"+o,"g");return n.map((n,t)=>(t?e[t-1]:"")+n.replace(r,"\n")).join("").replace(/^\n|\n$/g,"")}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment