all files / src/ weighted-dictionary.1.ts

38.46% Statements 10/26
0% Branches 0/10
16.67% Functions 1/6
38.1% Lines 8/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                                      
import * as Collections from "typescript-collections";
 
export class WeightedDictionary<T> extends Collections.Dictionary<T, number> {
    private _totalWeight = 0;
 
    constructor(toStrFunction?: (key: T) => string) {
        super(toStrFunction);
    }
 
    get totalWeight(): number {
        return this._totalWeight;
    }
 
    setValue(key: T, value: number): number {
        const prevVal = super.setValue(key, value);
        if (prevVal) { this._totalWeight -= prevVal; }
        if (value) { this._totalWeight += value; }
        return prevVal;
    }
 
    incrementValue(key: T, value: number): number {
        let newWeight = value;
        if (this.containsKey(key)) {
            newWeight += this.getValue(key);
        };
        return this.setValue(key, newWeight);
    }
 
    remove(key: T): number {
        const val = super.remove(key);
        if (val) { this._totalWeight -= val; }
        return val;
    }
};