Implement MergedMap pattern

This commit is contained in:
Tangent Wantwight 2024-07-14 22:19:26 -04:00
parent dc19a5ed9e
commit 63c41f07cb
2 changed files with 27 additions and 3 deletions

View file

@ -36,7 +36,7 @@ User: tirga
const idv = Idv.parse(textarea.value); const idv = Idv.parse(textarea.value);
pre.textContent = JSON.stringify( pre.textContent = JSON.stringify(
idv.getMap("User", UserFromDocument), idv.getMergedMap("User", UserFromDocument),
null, null,
2 2
); );
@ -49,8 +49,7 @@ User: tirga
return [textarea, pre]; return [textarea, pre];
} }
const UserFromDocument = (lines: string[]) => { const UserFromDocument = (idv: Idv) => {
const idv = Idv.parseLines(lines);
return { return {
shell: idv.getProperty("Shell", String, StringFromDocument), shell: idv.getProperty("Shell", String, StringFromDocument),
groups: idv.getList("Group", String, StringFromDocument), groups: idv.getList("Group", String, StringFromDocument),

View file

@ -1,5 +1,6 @@
export type DistinguisherParser<T> = (distinguisher: string) => T; export type DistinguisherParser<T> = (distinguisher: string) => T;
export type DocumentParser<T> = (document: string[]) => T; export type DocumentParser<T> = (document: string[]) => T;
export type IdvConverter<T> = (idv: Idv) => T;
const LEADING_WHITESPACE = /^([ \t]+)/; const LEADING_WHITESPACE = /^([ \t]+)/;
const ENTRY = /^(.+?):\s*(.*)/; const ENTRY = /^(.+?):\s*(.*)/;
@ -104,6 +105,30 @@ export class Idv {
]) ])
); );
} }
public getMergedMap<T>(
name: string,
convertIdv: IdvConverter<T>
): Record<string, T> {
const idvMap: Map<string, Idv> = 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<string, T> = {};
for (const [distinguisher, idv] of idvMap.entries()) {
result[distinguisher] = convertIdv(idv);
}
return result;
}
} }
export const StringFromDocument = (lines: string[]) => lines.join("\n"); export const StringFromDocument = (lines: string[]) => lines.join("\n");