import { CancellationTokenSource } from './cancellation.js';
class Cache {
    constructor(task) {
        this.task = task;
        this.result = null;
    }
    get() {
        if (this.result) {
            return this.result;
        }
        const cts = ( new CancellationTokenSource());
        const promise = this.task(cts.token);
        this.result = {
            promise,
            dispose: () => {
                this.result = null;
                cts.cancel();
                cts.dispose();
            }
        };
        return this.result;
    }
}
class LRUCachedFunction {
    constructor(fn, _computeKey = JSON.stringify) {
        this.fn = fn;
        this._computeKey = _computeKey;
        this.lastCache = undefined;
        this.lastArgKey = undefined;
    }
    get(arg) {
        const key = this._computeKey(arg);
        if (this.lastArgKey !== key) {
            this.lastArgKey = key;
            this.lastCache = this.fn(arg);
        }
        return this.lastCache;
    }
}
class CachedFunction {
    get cachedValues() {
        return this._map;
    }
    constructor(fn) {
        this.fn = fn;
        this._map = ( new Map());
    }
    get(arg) {
        if (( this._map.has(arg))) {
            return this._map.get(arg);
        }
        const value = this.fn(arg);
        this._map.set(arg, value);
        return value;
    }
}
export { Cache, CachedFunction, LRUCachedFunction };
