All files store.ts

81.82% Statements 27/33
100% Branches 8/8
70% Functions 7/10
80.65% Lines 25/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  6x 6x     6x 6x 6x 6x 6x 6x 6x 19x 19x 3x 19x 16x                             208x 45x 163x     23x 20x 3x 3x       20x     6x 6x 6x                                    
/*
 * @Author: lijianzhang
 * @Date: 2018-08-29 21:34:11
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2018-08-30 00:34:16
 */
import Observer from './observer';
import useLog from './log';
 
export class Store {
 
    queue: Set<number> = new Set();
 
    onError(error) {
        throw error;
    }
 
    stack = 0;
 
    useDebug = false;

    public useLog() {
        const unLog = useLog();
        this.unLog = () => {
            unLog();
            this.unLog = undefined;
        };
        return this.unLog;
    }
 
    unLog?: Function;
 
    public observers: Map<number, Observer> = new Map();
 
    public currentObservers: Observer[] = [];
 
    get currentObserver() {
        if (this.currentObservers.length === 0) return null;
        return this.currentObservers[this.currentObservers.length - 1];
    }
 
    private readyToRun: boolean = false;
 
    pushQueue(ids: Set<number>) {
        ids.forEach(id => this.queue.add(id));
 
        if (!this.inAction && !this.readyToRun) {
            Promise.resolve().then(this.runQueue);
            this.readyToRun = true;
        }
    }
  
    runQueue = () => {
        this.readyToRun = false;
        if (this.queue.size === 0) return;
        this.queue.forEach(id => this.observers.get(id).run());
        this.queue.clear();
    };
  
    get inAction(): boolean {
        return this.stack > 0;
    }
}
 
const store = new Store();
 
export default store;