3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-20 23:25:43 +01:00

Answer architecture round 3: the forecast never overcounts, the carry's JSON and the portable code block join through joinedWithin, and the list's choice of form stands in its own function

This commit is contained in:
2026-10-12 17:52:15 +02:00
committed by Lillem4n
parent 3414c8690a
commit ae1a47f1bc
14 changed files with 83 additions and 84 deletions
+7 -26
View File
@@ -7,51 +7,32 @@ type Member = { label: string; value: JsonValue }
type Pending = string | { depth: number; value: JsonValue }
export function serializeCanonicalJson(value: JsonValue, spelling: JsonSpelling): string {
const text: string[] = []
writeCanonicalJson(value, spelling, (piece) => {
text.push(piece)
return true
})
return text.join('')
}
// `undefined` where the spelling runs past `longest` characters, where it stops building.
export function serializeCanonicalJsonWithin(value: JsonValue, spelling: JsonSpelling, longest: number): string | undefined {
const text: string[] = []
let length = 0
const whole = writeCanonicalJson(value, spelling, (piece) => {
length += piece.length
text.push(piece)
return length <= longest
})
return whole ? text.join('') : undefined
return [...canonicalJsonPieces(value, spelling)].join('')
}
// Stops at the first piece that does not match `text`: re-spelled with two-space indentation, a short compact text can pass the engine's longest string.
export function spellsCanonicalJson(value: JsonValue, spelling: JsonSpelling, text: string): boolean {
let offset = 0
const whole = writeCanonicalJson(value, spelling, (piece) => {
for (const piece of canonicalJsonPieces(value, spelling)) {
if (!text.startsWith(piece, offset)) return false
offset += piece.length
return true
})
return whole && offset === text.length
}
return offset === text.length
}
function writeCanonicalJson(value: JsonValue, spelling: JsonSpelling, write: (piece: string) => boolean): boolean {
export function* canonicalJsonPieces(value: JsonValue, spelling: JsonSpelling): Generator<string> {
const indent = spelling === 'compact' ? '' : ' '
const pending: Pending[] = [{ depth: 0, value }]
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
if (typeof next === 'string') {
if (!write(next)) return false
yield next
continue
}
const { depth, value: held } = next
if (Array.isArray(held)) schedule(pending, '[', held.map((item) => ({ label: '', value: item })), ']', indent, depth)
else if (held !== null && typeof held === 'object') schedule(pending, '{', objectMembers(held, indent), '}', indent, depth)
else if (!write(Object.is(held, -0) ? '-0' : JSON.stringify(held))) return false
else yield Object.is(held, -0) ? '-0' : JSON.stringify(held)
}
return true
}
function objectMembers(value: { [key: string]: JsonValue }, indent: string): Member[] {