Created
December 15, 2015 12:23
-
-
Save jimschubert/06fea56a6d2a1e7fdbc2 to your computer and use it in GitHub Desktop.
ES6/ES2015 tag function to support "indented" strings like Scala's stripMargin function.
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
/** | |
* Allows Scala-like stripMargin | |
* | |
* Parameters are applied implicitly via ES2015. | |
* | |
* @example | |
* // returns "The Number is:\n 100\nThanks for playing!" | |
* let num = 100 | |
* let result = stripMargin`The Number is: | |
* | ${num} | |
* |Thanks for playing!` | |
* | |
*/ | |
export function stripMargin(template, ...expressions) { | |
let result = template.reduce((accumulator, part, i) => { | |
return accumulator + expressions[i - 1] + part | |
}) | |
return result.replace(/\r?(\n)\s*\|/g, '$1'); | |
} |
Thanks! Here's a TypeScript, Mac/Windows EOL compatible, linted version:
function stripMargin(template: TemplateStringsArray, ...expressions: any[]) {
const result = template.reduce((accumulator, part, i) => {
return accumulator + expressions[i - 1] + part;
});
return result.replace(/(\n|\r|\r\n)\s*\|/g, '$1');
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://codepen.io/jimschubert/pen/xZZmVV