UNPKG

@sap-cloud-sdk/util

Version:

SAP Cloud SDK for JavaScript general utilities

42 lines 1.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.codeBlock = codeBlock; const string_formatter_1 = require("./string-formatter"); 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 + string_formatter_1.unixEOL; }); pre.push(strings[strings.length - 1]); const indents = strings.slice(0, -1).map(s => { const indentation = s.split(string_formatter_1.unixEOL).pop(); return !indentation.trim() ? indentation : ''; }); const post = args.map((arg, i) => ('' + arg) .split(string_formatter_1.unixEOL) .map(subArg => indents[i] + subArg) .join(string_formatter_1.unixEOL)); const zipped = (0, array_1.zip)(pre, post); return (0, string_1.trim)(zipped.join('')); } function trimRightNewlines(string) { let subStrings = string.split(string_formatter_1.unixEOL); if (!subStrings[subStrings.length - 1].trim()) { subStrings = subStrings.slice(0, -1); } return subStrings.join(string_formatter_1.unixEOL); } //# sourceMappingURL=code-block.js.map