Skip to content
Snippets Groups Projects
Select Git revision
  • f16c699d3bfc5c2b92ddbfdc4aa890bc86cbe7d9
  • master default protected
  • rednatco-v2
  • base-pairs-ladder
  • 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
  • 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

hash-set.ts

Blame
  • user avatar
    David Sehnal authored
    f16c699d
    History
    hash-set.ts 1.42 KiB
    /**
     * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
     *
     * @author David Sehnal <david.sehnal@gmail.com>
     */
    
    interface SetLike<T> {
        readonly size: number;
        add(a: T): boolean;
        has(a: T): boolean;
    }
    
    class HashSetImpl<T> implements SetLike<T> {
        size: number = 0;
        private byHash = new Map<number, T[]>();
    
        add(a: T) {
            const hash = this.getHash(a);
            if (this.byHash.has(hash)) {
                const xs = this.byHash.get(hash)!;
                for (let i = 0, _i = xs.length; i < _i; i++) {
                    if (this.areEqual(a, xs[i])) return false;
                }
                xs[xs.length] = a;
                this.size++;
                return true;
            } else {
                this.byHash.set(hash, [a]);
                this.size++;
                return true;
            }
        }
    
        has(v: T) {
            const hash = this.getHash(v);
            if (!this.byHash.has(hash)) return false;
            const xs = this.byHash.get(hash)!;
            for (let i = 0, _i = xs.length; i < _i; i++) {
                if (this.areEqual(v, xs[i])) return true;
            }
            return false;
        }
    
        constructor(private getHash: (v: T) => any, private areEqual: (a: T, b: T) => boolean) { }
    }
    // TODO: add implementations with multilevel hashing support?
    
    export function HashSet<T>(getHash: (v: T) => any, areEqual: (a: T, b: T) => boolean): SetLike<T> {
        return new HashSetImpl<T>(getHash, areEqual);
    }