Skip to content
Snippets Groups Projects
Select Git revision
  • 157f51d9e25f80cfd4f89f179787e05f0787e6df
  • master default protected
  • rednatco-v2
  • rednatco
  • test
  • ntc-tube-uniform-color
  • ntc-tube-missing-atoms
  • restore-vertex-array-per-program
  • watlas2
  • dnatco_new
  • cleanup-old-nodejs
  • webmmb
  • fix_auth_seq_id
  • update_deps
  • ext_dev
  • ntc_balls
  • nci-2
  • plugin
  • bugfix-0.4.5
  • nci
  • servers
  • v0.5.0-dev.1
  • v0.4.5
  • v0.4.4
  • v0.4.3
  • v0.4.2
  • v0.4.1
  • v0.4.0
  • v0.3.12
  • v0.3.11
  • v0.3.10
  • v0.3.9
  • v0.3.8
  • v0.3.7
  • v0.3.6
  • v0.3.5
  • v0.3.4
  • v0.3.3
  • v0.3.2
  • v0.3.1
  • v0.3.0
41 results

backbone.ts

Blame
  • map.ts 1.25 KiB
    /**
     * 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
    //     }
    // }