UNPKG

@sap-cloud-sdk/util

Version:

SAP Cloud SDK for JavaScript general utilities

41 lines 1.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.codeBlock = codeBlock; const array_1 = require("./array"); const string_1 = require("./string"); /** * @experimental This API is experimental and might change in newer versions. Use with caution. * Transform strings and arguments to a string formatted as a code block, keeping the indentation of sub code blocks. * Use in tagged templates, e.g.: * ``` * codeBlock`Code with ${arguments} and more code;` * ``` * @param strings - Strings in the tagged template. In the example above that would be ['Code with ', ' and more code;']. * @param args - Arguments in the tagged template. In the example above that would be the resolved value for `arguments`;. * @returns A string formatted as code block. */ function codeBlock(strings, ...args) { const pre = strings.slice(0, -1).map(string => { const trimmed = trimRightNewlines(string); return trimmed.length === string.length ? string : `${trimmed}\n`; }); pre.push(strings[strings.length - 1]); const indents = strings.slice(0, -1).map(s => { const indentation = s.split('\n').pop(); return !indentation.trim() ? indentation : ''; }); const post = args.map((arg, i) => ('' + arg) .split('\n') .map(subArg => indents[i] + subArg) .join('\n')); const zipped = (0, array_1.zip)(pre, post); return (0, string_1.trim)(zipped.join('')); } function trimRightNewlines(string) { let subStrings = string.split('\n'); if (!subStrings[subStrings.length - 1].trim()) { subStrings = subStrings.slice(0, -1); } return subStrings.join('\n'); } //# sourceMappingURL=code-block.js.map