From 978df7253cd4281ee18e449a4c33919d22ca6692 Mon Sep 17 00:00:00 2001 From: pietervdvn Date: Fri, 24 Jun 2022 16:47:00 +0200 Subject: [PATCH] Improve typing --- UI/i18n/Translation.ts | 6 +++--- Utils.ts | 30 ++++++++++++++++++++++++------ scripts/generateStats.ts | 4 ++-- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/UI/i18n/Translation.ts b/UI/i18n/Translation.ts index 8d65e202b..4000ca97e 100644 --- a/UI/i18n/Translation.ts +++ b/UI/i18n/Translation.ts @@ -7,10 +7,10 @@ export class Translation extends BaseUIElement { public static forcedLanguage = undefined; - public readonly translations: object + public readonly translations: Record context?: string; - constructor(translations: object, context?: string) { + constructor(translations: Record, context?: string) { super() if (translations === undefined) { console.error("Translation without content at "+context) @@ -264,7 +264,7 @@ export class Translation extends BaseUIElement { } export class TypedTranslation extends Translation { - constructor(translations: object, context?: string) { + constructor(translations: Record, context?: string) { super(translations, context); } diff --git a/Utils.ts b/Utils.ts index ff93b6e88..c6e5073e5 100644 --- a/Utils.ts +++ b/Utils.ts @@ -931,20 +931,38 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be return track[str2.length][str1.length]; } - public static MapToObj(d: Map, onValue: ((t: T, key: string) => any) = undefined): object { + public static MapToObj(d: Map, onValue: ((t: V, key: string) => T)): Record { const o = {} const keys = Array.from(d.keys()) keys.sort(); for (const key of keys) { - let value = d.get(key) - if (onValue !== undefined) { - value = onValue(value, key) - } - o[key] = value; + o[key] = onValue(d.get(key), key); } return o } + /** + * Switches keys and values around + * + * Utils.TransposeMap({"a" : ["b", "c"], "x" : ["b", "y"]}) // => {"b" : ["a", "x"], "c" : ["a"], "y" : ["x"]} + */ + public static TransposeMap(d: Record) : Record{ + const newD : Record = {}; + + for (const k in d) { + const vs = d[k] + for (let v of vs) { + const list = newD[v] + if(list === undefined){ + newD[v] = [k] // Left: indexing; right: list with one element + }else{ + list.push(k) + } + } + } + return newD; + } + /** * Utils.colorAsHex({r: 255, g: 128, b: 0}) // => "#ff8000" * Utils.colorAsHex(undefined) // => undefined diff --git a/scripts/generateStats.ts b/scripts/generateStats.ts index aa0813087..8ad991945 100644 --- a/scripts/generateStats.ts +++ b/scripts/generateStats.ts @@ -66,8 +66,8 @@ async function main(includeTags = true) { writeFileSync("./assets/key_totals.json", JSON.stringify( { - keys: Utils.MapToObj(keyTotal), - tags: Utils.MapToObj(tagTotal, v => Utils.MapToObj(v)) + keys: Utils.MapToObj(keyTotal, t => t), + tags: Utils.MapToObj(tagTotal, v => Utils.MapToObj(v, t => t)) }, null, " " )