MCPcopy Create free account
hub / github.com/antfu/utils / unindent

Function unindent

src/string.ts:124–147  ·  view source on GitHub ↗
(str: TemplateStringsArray | string)

Source from the content-addressed store, hash-verified

122 * `
123 */
124export function unindent(str: TemplateStringsArray | string) {
125 const lines = (typeof str === 'string' ? str : str[0]).split('\n')
126 const whitespaceLines = lines.map(line => _reFullWs.test(line))
127
128 const commonIndent = lines
129 .reduce((min, line, idx) => {
130 if (whitespaceLines[idx])
131 return min
132 const indent = line.match(/^\s*/)?.[0].length
133 return indent === undefined ? min : Math.min(min, indent)
134 }, Number.POSITIVE_INFINITY)
135
136 let emptyLinesHead = 0
137 while (emptyLinesHead < lines.length && whitespaceLines[emptyLinesHead])
138 emptyLinesHead++
139 let emptyLinesTail = 0
140 while (emptyLinesTail < lines.length && whitespaceLines[lines.length - emptyLinesTail - 1])
141 emptyLinesTail++
142
143 return lines
144 .slice(emptyLinesHead, lines.length - emptyLinesTail)
145 .map(line => line.slice(commonIndent))
146 .join('\n')
147}

Callers 1

string.test.tsFile · 0.90

Calls 2

mapMethod · 0.80
reduceMethod · 0.80

Tested by

no test coverage detected