refactor: simplify normalization logic for arrays and objects

This commit is contained in:
Johann Schopplich
2025-10-23 15:14:32 +02:00
parent 42b06db4a5
commit 8baff48b3c
2 changed files with 15 additions and 38 deletions

View File

@@ -140,15 +140,8 @@ export function encodeInlinePrimitiveArray(
depth: Depth, depth: Depth,
options: ResolvedEncodeOptions, options: ResolvedEncodeOptions,
): void { ): void {
const header = formatHeader(values.length, prefix ? { key: prefix } : undefined) const formatted = formatInlineArray(values, options.delimiter, prefix)
const joinedValue = joinEncodedValues(values, options.delimiter) writer.push(depth, formatted)
// Only add space if there are values
if (values.length === 0) {
writer.push(depth, header)
}
else {
writer.push(depth, `${header} ${joinedValue}`)
}
} }
// #endregion // #endregion
@@ -173,8 +166,8 @@ export function encodeArrayOfArraysAsListItems(
} }
} }
export function formatInlineArray(values: readonly JsonPrimitive[], delimiter: string): string { export function formatInlineArray(values: readonly JsonPrimitive[], delimiter: string, prefix?: string): string {
const header = formatHeader(values.length) const header = formatHeader(values.length, prefix ? { key: prefix } : undefined)
const joinedValue = joinEncodedValues(values, delimiter) const joinedValue = joinEncodedValues(values, delimiter)
// Only add space if there are values // Only add space if there are values
if (values.length === 0) { if (values.length === 0) {

View File

@@ -46,12 +46,12 @@ export function normalizeValue(value: unknown): JsonValue {
// Array // Array
if (Array.isArray(value)) { if (Array.isArray(value)) {
return normalizeArray(value) return value.map(normalizeValue)
} }
// Set → array // Set → array
if (value instanceof Set) { if (value instanceof Set) {
return normalizeArray(Array.from(value)) return Array.from(value).map(normalizeValue)
} }
// Map → object // Map → object
@@ -63,26 +63,6 @@ export function normalizeValue(value: unknown): JsonValue {
// Plain object // Plain object
if (isPlainObject(value)) { if (isPlainObject(value)) {
return normalizeObject(value)
}
// Fallback: function, symbol, undefined, or other → null
return null
}
export function normalizeArray(value: unknown): JsonArray {
if (!Array.isArray(value)) {
return []
}
return value.map(item => normalizeValue(item))
}
export function normalizeObject(value: unknown): JsonObject {
if (!isPlainObject(value)) {
return {}
}
const result: Record<string, JsonValue> = {} const result: Record<string, JsonValue> = {}
for (const key in value) { for (const key in value) {
@@ -92,6 +72,10 @@ export function normalizeObject(value: unknown): JsonObject {
} }
return result return result
}
// Fallback: function, symbol, undefined, or other → null
return null
} }
// #endregion // #endregion