UNPKG

shift-tab

Version:

Removes indent space from multiline strings

70 lines 2.77 kB
import { buildTemplate, count, isEmptyOrWhitespace } from "./utils.js"; export function shiftTab(...args) { if (typeof args[0] === "object" && !Array.isArray(args[0])) { return shiftTab.bind(args[0]); } else { let str = typeof args[0] === "string" ? args[0] : buildTemplate(...args); const { indent = "first", pad, trim = "wrap", process } = this ?? {}; let lines = str.split("\n"); let wsChar = ""; const countIndent = (str) => { const size = count(str, ch => { if (!wsChar && (ch === " " || ch === "\t")) { wsChar = ch; } return ch === wsChar; }); return isEmptyOrWhitespace(str) ? -1 : size; }; let lineIndents = lines.map(countIndent); if (trim === "lines") { const leading = count(lines, isEmptyOrWhitespace); const trailing = count(lines, isEmptyOrWhitespace, true); lines = lines.slice(leading, -trailing || undefined); lineIndents = lineIndents.slice(leading, -trailing); } else if (trim === "wrap") { if (lines[0] === "") { lines.shift(); lineIndents.shift(); } if (isEmptyOrWhitespace(lines[lines.length - 1])) { lines.pop(); lineIndents.pop(); } } if (indent === "all") { lines = lines.map((line, i) => line.substring(lineIndents[i])); } else { let indentSize = indent === "first" ? lineIndents.find(_ => _ > -1) // : Math.min(...lineIndents.filter(_ => _ !== -1)); if (indentSize !== undefined && indentSize > 0) { const size = indentSize; lines = lines.map((line, i) => line.substring(Math.min(size, lineIndents[i]))); } if (typeof indent === "number") { const pad = wsChar.repeat(indent); lines = lines.map(line => pad + line); } } if (pad || typeof pad === "number") { const padSize = typeof pad === "number" ? pad : Math.max(...lines.map(line => line.length)); lines = lines.map(line => line.padEnd(padSize, " ")); } else { lines = lines.map(line => line.trimEnd()); } let result = lines.join("\n"); if (process) { result = process.reduce((acc, processor) => { const processed = processor(acc); return typeof processed === "string" ? processed : acc; }, result); } return result; } } //# sourceMappingURL=shift-tab.js.map