Skip to content

Commit 936b3f6

Browse files
lilliliililfatfisz
authored andcommitted
A little better RegExps and refactor (#130)
* A little better RegExps and refactor * Return early * Remove \r from regexps
1 parent 62ff633 commit 936b3f6

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

Diff for: src/stripIndent/stripIndent.test.js

+6
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,9 @@ test('does nothing if there are no indents', async (t) => {
4848
const actual = stripIndent`wow such doge`
4949
t.is(actual, expected)
5050
})
51+
52+
test('does nothing if minimal indent has zero length', async (t) => {
53+
const expected = 'wow\n such\n doge'
54+
const actual = stripIndent`wow\n such\n doge`
55+
t.is(actual, expected)
56+
})

Diff for: src/stripIndentTransformer/stripIndentTransformer.js

+10-12
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,19 @@ const stripIndentTransformer = (type = 'initial') => ({
99
onEndResult (endResult) {
1010
if (type === 'initial') {
1111
// remove the shortest leading indentation from each line
12-
const match = endResult.match(/^[ \t]*(?=\S)/gm)
13-
// return early if there's nothing to strip
14-
if (match === null) {
15-
return endResult
12+
const match = endResult.match(/^[^\S\n]*(?=\S)/gm)
13+
const indent = match && Math.min(...match.map(el => el.length))
14+
if (indent) {
15+
const regexp = new RegExp(`^.{${indent}}`, 'gm')
16+
return endResult.replace(regexp, '')
1617
}
17-
const indent = Math.min(...match.map(el => el.length))
18-
const regexp = new RegExp('^[ \\t]{' + indent + '}', 'gm')
19-
endResult = indent > 0 ? endResult.replace(regexp, '') : endResult
20-
} else if (type === 'all') {
18+
return endResult
19+
}
20+
if (type === 'all') {
2121
// remove all indentation from each line
22-
endResult = endResult.replace(/(?:\n[^\S\n]*)/g, '\n')
23-
} else {
24-
throw new Error(`Unknown type: ${type}`)
22+
return endResult.replace(/^[^\S\n]+/gm, '')
2523
}
26-
return endResult
24+
throw new Error(`Unknown type: ${type}`)
2725
}
2826
})
2927

0 commit comments

Comments
 (0)