Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions yaml/_dumper_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ export interface DumperStateOptions {
* if first argument is less than second argument, zero if they're equal
* and a positive value otherwise.
*/
sortKeys?: boolean | ((a: string, b: string) => number);
sortKeys?: boolean | ((a: string, b: string, depth: number) => number);
/** set max line width. (default: 80) */
lineWidth?: number;
/**
Expand Down Expand Up @@ -467,7 +467,7 @@ export class DumperState {
arrayIndent: boolean;
skipInvalid: boolean;
flowLevel: number;
sortKeys: boolean | ((a: string, b: string) => number);
sortKeys: boolean | ((a: string, b: string, depth: number) => number);
lineWidth: number;
useAnchors: boolean;
compatMode: boolean;
Expand Down Expand Up @@ -667,7 +667,8 @@ export class DumperState {
keys.sort();
} else if (typeof this.sortKeys === "function") {
// Custom sort function
keys.sort(this.sortKeys);
const sortKeys = this.sortKeys;
keys.sort((a, b) => sortKeys(a, b, level));
} else if (this.sortKeys) {
// Something is wrong
throw new TypeError(
Expand Down
2 changes: 1 addition & 1 deletion yaml/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export type StringifyOptions = {
*
* @default {false}
*/
sortKeys?: boolean | ((a: string, b: string) => number);
sortKeys?: boolean | ((a: string, b: string, depth: number) => number);
/**
* Set max line width.
*
Expand Down
10 changes: 10 additions & 0 deletions yaml/stringify_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,16 @@ Deno.test("stringify() changes the key order when the sortKeys option is specifi
);
});

Deno.test("stringify() passes depth to sortKeys callback", () => {
const input = { b: 1, a: 2, nested: { c: 3, d: 4 } };
const sortKeys = (a: string, b: string, depth: number) =>
depth === 0 ? a.localeCompare(b) : b.localeCompare(a);
const expected = ["a: 2", "b: 1", "nested:", " d: 4", " c: 3", ""].join(
"\n",
);
assertEquals(stringify(input, { sortKeys }), expected);
});

Deno.test("stringify() changes line wrap behavior based on lineWidth option", () => {
const object = {
message:
Expand Down
Loading