From 63c41f07cbe3b8249aa41f7b4cf5c0ed3c88eafe Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Sun, 14 Jul 2024 22:19:26 -0400 Subject: [PATCH] Implement MergedMap pattern --- debug/idv.ts | 5 ++--- lib/idv.ts | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/debug/idv.ts b/debug/idv.ts index de17339..7583dbe 100644 --- a/debug/idv.ts +++ b/debug/idv.ts @@ -36,7 +36,7 @@ User: tirga const idv = Idv.parse(textarea.value); pre.textContent = JSON.stringify( - idv.getMap("User", UserFromDocument), + idv.getMergedMap("User", UserFromDocument), null, 2 ); @@ -49,8 +49,7 @@ User: tirga return [textarea, pre]; } -const UserFromDocument = (lines: string[]) => { - const idv = Idv.parseLines(lines); +const UserFromDocument = (idv: Idv) => { return { shell: idv.getProperty("Shell", String, StringFromDocument), groups: idv.getList("Group", String, StringFromDocument), diff --git a/lib/idv.ts b/lib/idv.ts index 4db02a6..b0c753a 100644 --- a/lib/idv.ts +++ b/lib/idv.ts @@ -1,5 +1,6 @@ export type DistinguisherParser = (distinguisher: string) => T; export type DocumentParser = (document: string[]) => T; +export type IdvConverter = (idv: Idv) => T; const LEADING_WHITESPACE = /^([ \t]+)/; const ENTRY = /^(.+?):\s*(.*)/; @@ -104,6 +105,30 @@ export class Idv { ]) ); } + + public getMergedMap( + name: string, + convertIdv: IdvConverter + ): Record { + const idvMap: Map = new Map(); + + (this.collections[name] ?? []).forEach(([distinguisher, document]) => { + let idv = idvMap.get(distinguisher); + if (idv == undefined) { + idvMap.set(distinguisher, (idv = new Idv())); + } + + idv.importLines(document); + }); + + const result: Record = {}; + + for (const [distinguisher, idv] of idvMap.entries()) { + result[distinguisher] = convertIdv(idv); + } + + return result; + } } export const StringFromDocument = (lines: string[]) => lines.join("\n");