Skip to content

Commit

Permalink
🤦‍♀️ ignore empty lines (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsslldnphy authored Mar 21, 2024
1 parent b75cec2 commit 222e874
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
21 changes: 21 additions & 0 deletions src/unindent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,25 @@ describe("unindent", () => {
content TEXT NOT NULL
)`);
});

test("it handles empty lines in the middle of the string", () => {
expect(unindent`
CREATE TABLE posts (
id UUID NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL
)
`).toEqual(`CREATE TABLE posts (
id UUID NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL
)`);
});
});
14 changes: 10 additions & 4 deletions src/unindent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@ export const unindent = (strings: TemplateStringsArray) => {
const joined = strings.join("");
const lines = joined.split("\n");

// strip any leading empty lines
while (lines[0]?.replace(/\s*/, "") === "") {
lines.splice(0, 1);
}

// strip any traling empty lines
while (lines[lines.length - 1]?.replace(/\s*/, "") === "") {
lines.splice(lines.length - 1, 1);
}

const indent =
Math.min(
...lines.map((s) => s.length - s.replace(/^\s+/, "").length),
) ?? 0;
const indents = lines
// ignore any blank lines when calculating indents
.filter((l) => l.replace(/\s*/, "") !== "")
// get the number of whitespace characters before the first non-whitespace character
.map((s) => s.length - s.replace(/^\s+/, "").length);

// take the smallest indent: this is how much we're going to unindent by
const indent = Math.min(...indents) ?? 0;

return lines.map((s) => s.substring(indent)).join("\n");
};

0 comments on commit 222e874

Please sign in to comment.