Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Last active July 21, 2024 17:18
Show Gist options
  • Save colelawrence/52cd872480e160447eb3ec68bc0d4ff0 to your computer and use it in GitHub Desktop.
Save colelawrence/52cd872480e160447eb3ec68bc0d4ff0 to your computer and use it in GitHub Desktop.
unindent-template-array.ts
const INDENTATION_RE = /^\n( +)/;
const unindentTemplate = (
template: TemplateStringsArray,
): { readonly raw: readonly string[] } => {
const indentation = INDENTATION_RE.exec(template.raw[0])?.[1];
return indentation
? { raw: template.raw.map((a) => a.replaceAll(`\n${indentation}`, "\n")) }
: template;
};
// example usage in another template function for markdown
const escapeMarkdown = (markdown: string) => markdown.replace(/(`)/g, "\\$1");
export type Markdown = { readonly MARKDOWN: string };
/** escape text substitutions for Markdown */
export const md = (
template: TemplateStringsArray,
...substitutions: (Markdown | number | string | Record<string, unknown>)[]
) => {
const subs = substitutions.map((a) =>
typeof a === "object" && "MARKDOWN" in a
? a.MARKDOWN
: escapeMarkdown(devStringify(a)),
);
return { MARKDOWN: String.raw(unindentTemplate(template), ...subs) };
};
// usage
function something() {
// has trailing new line
const ex1 = md`
# Hello world
- Good day
`
// no trailing new line
const ex2 = md`
# Hello world
- Good day`
// no indentation changes (same as ex1)
const ex3 = md`# Hello world
- Good day
`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment