chore(test): add template literal for trimming indentation

This commit is contained in:
Elian Doran 2024-12-17 23:08:17 +02:00
parent 7bae719309
commit ba95caaf6d
No known key found for this signature in database
2 changed files with 35 additions and 0 deletions

View File

@ -0,0 +1,14 @@
import { trimIndentation } from "./utils.js";
describe("Utils", () => {
it("trims indentation", () => {
expect(trimIndentation`\
Hello
world
123`
).toBe(`\
Hello
world
123`);
});
});

21
spec/support/utils.ts Normal file
View File

@ -0,0 +1,21 @@
export function trimIndentation(strings: TemplateStringsArray) {
const str = strings.toString();
// Count the number of spaces on the first line.
let numSpaces = 0;
while (str.charAt(numSpaces) == ' ' && numSpaces < str.length) {
numSpaces++;
}
// Trim the indentation of the first line in all the lines.
const lines = str.split("\n");
const output = [];
for (let i=0; i<lines.length; i++) {
let numSpacesLine = 0;
while (str.charAt(numSpacesLine) == ' ' && numSpacesLine < str.length) {
numSpacesLine++;
}
output.push(lines[i].substring(numSpacesLine));
}
return output.join("\n");
}