Skip to content

Commit

Permalink
refactor(yaml): simplify and rename dropEndingNewline() (#5336)
Browse files Browse the repository at this point in the history
  • Loading branch information
timreichen authored Jul 7, 2024
1 parent ce0c1e2 commit 424a113
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
11 changes: 4 additions & 7 deletions yaml/_dumper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,9 +436,8 @@ function foldLine(line: string, width: number): string {
return result.slice(1); // drop extra \n joiner
}

// (See the note for writeScalar.)
function dropEndingNewline(string: string): string {
return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
export function trimTrailingNewline(string: string) {
return string.at(-1) === "\n" ? string.slice(0, -1) : string;
}

// Note: a long line without a suitable break point will exceed the width limit.
Expand Down Expand Up @@ -583,13 +582,11 @@ function writeScalar(
return `'${string.replace(/'/g, "''")}'`;
case STYLE_LITERAL:
return `|${blockHeader(string, state.indent)}${
dropEndingNewline(
indentString(string, indent),
)
trimTrailingNewline(indentString(string, indent))
}`;
case STYLE_FOLDED:
return `>${blockHeader(string, state.indent)}${
dropEndingNewline(
trimTrailingNewline(
indentString(foldString(string, lineWidth), indent),
)
}`;
Expand Down
13 changes: 13 additions & 0 deletions yaml/_dumper_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import { assertEquals } from "@std/assert";
import { trimTrailingNewline } from "./_dumper.ts";

Deno.test("trimTrailingNewline()", async (t) => {
await t.step("handles string without trailing newline", () => {
assertEquals(trimTrailingNewline("hello\nworld"), "hello\nworld");
});
await t.step("handles string with trailing newline", () => {
assertEquals(trimTrailingNewline("hello\nworld\n"), "hello\nworld");
});
});

0 comments on commit 424a113

Please sign in to comment.