From be1b2a1c3e0418620147b89a69b6d6b610277eb1 Mon Sep 17 00:00:00 2001
From: Alexander Rose <alex.rose@rcsb.org>
Date: Fri, 17 Aug 2018 12:08:32 -0700
Subject: [PATCH] added DefaultMap

---
 src/mol-util/map.ts | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
 create mode 100644 src/mol-util/map.ts

diff --git a/src/mol-util/map.ts b/src/mol-util/map.ts
new file mode 100644
index 000000000..42c258907
--- /dev/null
+++ b/src/mol-util/map.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author Alexander Rose <alexander.rose@weirdbyte.de>
+ */
+
+export interface DefaultMap<K, V> extends Map<K, V> {
+    /** Return the value for `key` when available or the default value otherwise. */
+    getDefault: (key: K) => V
+}
+
+/** A `Map` instance with a `getDefault` method added. */
+export function DefaultMap<K, V>(valueCtor: () => V) {
+    const map = new Map<K, V>() as DefaultMap<K, V>
+    map.getDefault = (key: K) => {
+        if (map.has(key)) return map.get(key)!
+        const value = valueCtor()
+        map.set(key, value)
+        return value
+    }
+    return map
+}
+
+// TODO currently not working, see https://github.com/Microsoft/TypeScript/issues/10853
+// /** A `Map` with a `getDefault` method added. */
+// export class DefaultMap<K, V> extends Map<K, V> {
+//     constructor(private valueCtor: () => V, entries?: ReadonlyArray<[K, V]>) {
+//         super(entries)
+//     }
+//     /** Return the value for `key` when available or the default value otherwise. */
+//     getDefault(key: K) {
+//         if (this.has(key)) return this.get(key)!
+//         const value = this.valueCtor()
+//         this.set(key, value)
+//         return value
+//     }
+// }
\ No newline at end of file
-- 
GitLab