refactor IDV parser to use map why not

This commit is contained in:
Tangent Wantwight 2024-07-20 00:08:32 -04:00
parent 6c6c9386be
commit af07866ac0
2 changed files with 11 additions and 8 deletions

View file

@ -7,7 +7,7 @@ const LEADING_WHITESPACE = /^([ \t]+)/;
const ENTRY = /^(.+?):\s*(.*)/;
export class Idv {
collections: Record<string, undefined | [string, string[]][]> = {};
collections: Map<string, undefined | [string, string[]][]> = new Map();
public static parse(input: string): Idv {
const idv = new Idv();
@ -53,14 +53,16 @@ export class Idv {
if (matches) {
const [, collection, distinguisher] = matches;
if (this.collections[collection] == undefined) {
this.collections[collection] = [];
if (!this.collections.has(collection)) {
this.collections.set(collection, []);
}
currentDocument = [];
currentIndent = undefined;
// TODO: implement backslash escaping in the distinguisher
this.collections[collection].push([distinguisher, currentDocument]);
this.collections
.get(collection)!
.push([distinguisher, currentDocument]);
} else {
throw new Error("Failed to parse a property");
}
@ -71,12 +73,12 @@ export class Idv {
}
public getProperty<T>(name: string, parse: UnionParser<T>): T | undefined {
const firstEntry = this.collections[name]?.[0];
const firstEntry = this.collections.get(name)?.[0];
return firstEntry && parse(firstEntry[0], firstEntry[1]);
}
public getList<T>(name: string, parse: UnionParser<T>): T[] {
return (this.collections[name] ?? []).map(([distinguisher, document]) =>
return (this.collections.get(name) ?? []).map(([distinguisher, document]) =>
parse(distinguisher, document)
);
}
@ -86,7 +88,7 @@ export class Idv {
parseDocument: DocumentParser<T>
): Record<string, T> {
return Object.fromEntries(
(this.collections[name] ?? []).map(([distinguisher, document]) => [
(this.collections.get(name) ?? []).map(([distinguisher, document]) => [
distinguisher,
parseDocument(document),
])
@ -99,7 +101,7 @@ export class Idv {
): Record<string, T> {
const idvMap: Map<string, Idv> = new Map();
(this.collections[name] ?? []).forEach(([distinguisher, document]) => {
(this.collections.get(name) ?? []).forEach(([distinguisher, document]) => {
let idv = idvMap.get(distinguisher);
if (idv == undefined) {
idvMap.set(distinguisher, (idv = new Idv()));

View file

@ -3,6 +3,7 @@
"isolatedModules": true,
"lib": ["ES2019", "DOM"],
"strict": true,
"target": "ES2020",
"noEmit": true
}
}