mirror of
https://github.com/voson-wang/toon.git
synced 2026-01-29 15:24:10 +08:00
refactor: simplify normalization logic for arrays and objects
This commit is contained in:
@@ -140,15 +140,8 @@ export function encodeInlinePrimitiveArray(
|
||||
depth: Depth,
|
||||
options: ResolvedEncodeOptions,
|
||||
): void {
|
||||
const header = formatHeader(values.length, prefix ? { key: prefix } : undefined)
|
||||
const joinedValue = joinEncodedValues(values, options.delimiter)
|
||||
// Only add space if there are values
|
||||
if (values.length === 0) {
|
||||
writer.push(depth, header)
|
||||
}
|
||||
else {
|
||||
writer.push(depth, `${header} ${joinedValue}`)
|
||||
}
|
||||
const formatted = formatInlineArray(values, options.delimiter, prefix)
|
||||
writer.push(depth, formatted)
|
||||
}
|
||||
|
||||
// #endregion
|
||||
@@ -173,8 +166,8 @@ export function encodeArrayOfArraysAsListItems(
|
||||
}
|
||||
}
|
||||
|
||||
export function formatInlineArray(values: readonly JsonPrimitive[], delimiter: string): string {
|
||||
const header = formatHeader(values.length)
|
||||
export function formatInlineArray(values: readonly JsonPrimitive[], delimiter: string, prefix?: string): string {
|
||||
const header = formatHeader(values.length, prefix ? { key: prefix } : undefined)
|
||||
const joinedValue = joinEncodedValues(values, delimiter)
|
||||
// Only add space if there are values
|
||||
if (values.length === 0) {
|
||||
|
||||
@@ -46,12 +46,12 @@ export function normalizeValue(value: unknown): JsonValue {
|
||||
|
||||
// Array
|
||||
if (Array.isArray(value)) {
|
||||
return normalizeArray(value)
|
||||
return value.map(normalizeValue)
|
||||
}
|
||||
|
||||
// Set → array
|
||||
if (value instanceof Set) {
|
||||
return normalizeArray(Array.from(value))
|
||||
return Array.from(value).map(normalizeValue)
|
||||
}
|
||||
|
||||
// Map → object
|
||||
@@ -63,26 +63,6 @@ export function normalizeValue(value: unknown): JsonValue {
|
||||
|
||||
// Plain object
|
||||
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> = {}
|
||||
|
||||
for (const key in value) {
|
||||
@@ -94,6 +74,10 @@ export function normalizeObject(value: unknown): JsonObject {
|
||||
return result
|
||||
}
|
||||
|
||||
// Fallback: function, symbol, undefined, or other → null
|
||||
return null
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region Type guards
|
||||
|
||||
Reference in New Issue
Block a user