Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(yaml): cleanup inspectNode() #5311

Merged
merged 1 commit into from
Jul 4, 2024
Merged
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
45 changes: 15 additions & 30 deletions yaml/_dumper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { YamlError } from "./_error.ts";
import { DEFAULT_SCHEMA, type Schema } from "./_schema.ts";
import type { RepresentFn, StyleVariant, Type } from "./_type.ts";
import * as common from "./_utils.ts";
import { isObject } from "./_utils.ts";

type Any = common.Any;
type ArrayObject<T = Any> = common.ArrayObject<T>;
Expand Down Expand Up @@ -902,30 +903,16 @@ function writeNode(
return true;
}

function inspectNode(
object: Any,
objects: Any[],
duplicatesIndexes: number[],
) {
if (object !== null && typeof object === "object") {
const index = objects.indexOf(object);
if (index !== -1) {
if (!duplicatesIndexes.includes(index)) {
duplicatesIndexes.push(index);
}
} else {
objects.push(object);

if (Array.isArray(object)) {
for (let idx = 0; idx < object.length; idx += 1) {
inspectNode(object[idx], objects, duplicatesIndexes);
}
} else {
for (const objectKey of Object.keys(object)) {
inspectNode(object[objectKey], objects, duplicatesIndexes);
}
}
}
function inspectNode(object: Any, objects: Any[], duplicateObjects: Set<Any>) {
if (!isObject(object)) return;
if (objects.includes(object)) {
duplicateObjects.add(object);
return;
}
objects.push(object);
const entries = Array.isArray(object) ? object : Object.values(object);
for (const value of entries) {
inspectNode(value, objects, duplicateObjects);
}
}

Expand All @@ -934,14 +921,12 @@ function getDuplicateReferences(
state: DumperState,
) {
const objects: Any[] = [];
const duplicatesIndexes: number[] = [];
const duplicateObjects: Set<Any> = new Set();

inspectNode(object, objects, duplicatesIndexes);
inspectNode(object, objects, duplicateObjects);

for (const idx of duplicatesIndexes) {
state.duplicates.push(objects[idx]);
}
state.usedDuplicates = Array.from({ length: duplicatesIndexes.length });
for (const object of duplicateObjects) state.duplicates.push(object);
state.usedDuplicates = Array.from({ length: duplicateObjects.size });
}

export function dump(input: Any, options: DumperStateOptions = {}): string {
Expand Down