/** Small helpers for reading and editing a block tree in place. */ import type { BlkBlock, BlkParam, BlkValue } from './model.ts'; export function findBlock(block: BlkBlock, name: string): BlkBlock | undefined { return block.blocks.find((child) => child.name === name); } export function findParam(block: BlkBlock, name: string): BlkParam | undefined { return block.params.find((param) => param.name === name); } /** Return the first sub-block called `name`, adding an empty one if there is none. */ export function ensureBlock(block: BlkBlock, name: string): BlkBlock { const existing = findBlock(block, name); if (existing) return existing; const created: BlkBlock = { name, params: [], blocks: [] }; block.blocks.push(created); return created; } /** Give the first parameter called `name` this value, or append one; later duplicates are removed. */ export function setParam(block: BlkBlock, name: string, value: BlkValue): void { const index = block.params.findIndex((param) => param.name === name); if (index < 0) { block.params.push({ name, value }); return; } block.params[index] = { name, value }; block.params = block.params.filter((param, position) => position <= index || param.name !== name); } /** Append a parameter called `name` without touching existing parameters of the same name (for repeated BLK keys such as `aircraftGift:t`). */ export function appendParam(block: BlkBlock, name: string, value: BlkValue): void { block.params.push({ name, value }); } /** Visit every parameter of the tree, depth first, with the path of block names leading to it. */ export function visitParams(block: BlkBlock, visit: (param: BlkParam, path: readonly string[]) => void, path: readonly string[] = []): void { for (const param of block.params) visit(param, path); for (const child of block.blocks) visitParams(child, visit, [...path, child.name]); }