Skip to content

Commit cde80aa

Browse files
committed
Rewrite the dedent loop without a closure
1 parent 03e2ed0 commit cde80aa

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

fluent-dedent/src/index.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,36 @@ export default function ftl(
1919
let code = strings.reduce((acc, cur) => acc + values.shift() + cur);
2020
let lines = code.split("\n");
2121

22-
const first = lines.shift();
22+
let first = lines.shift();
2323
if (first === undefined || !RE_BLANK.test(first)) {
2424
throw new RangeError("Content must start on a new line.");
2525
}
2626

27-
const commonIndent = lines.pop();
27+
let commonIndent = lines.pop();
2828
if (commonIndent === undefined || !RE_BLANK.test(commonIndent)) {
2929
throw new RangeError("Closing delimiter must appear on a new line.");
3030
}
3131

32-
return lines.map((line: string, idx: number): string => {
32+
let dedented = [];
33+
for (let i = 0; i < lines.length; i++) {
34+
let line = lines[i];
3335
let lineIndent = line.slice(0, commonIndent.length);
3436
if (lineIndent.length === 0) {
3537
// Empty blank lines are preserved even if technically they are not
3638
// indented at all. This also short-circuits the dedentation logic when
3739
// commonIndent.length is 0, i.e. when all indents should be kept.
38-
return line;
40+
dedented.push(line);
41+
continue;
3942
}
43+
4044
if (lineIndent !== commonIndent) {
4145
// The indentation of the line must match commonIndent exacty.
42-
throw new RangeError(`Insufficient indentation in line ${idx + 1}.`);
46+
throw new RangeError(`Insufficient indentation in line ${i + 1}.`);
4347
}
48+
4449
// Strip commonIndent.
45-
return line.slice(commonIndent.length);
46-
}).join("\n");
50+
dedented.push(line.slice(commonIndent.length));
51+
}
52+
53+
return dedented.join("\n");
4754
}

0 commit comments

Comments
 (0)