Move Cache under Async but keep re-exporting it for backwards compatibility

This commit is contained in:
Tissevert 2021-01-07 21:35:09 +01:00
parent 80355cd86d
commit 0a0af17124
2 changed files with 54 additions and 51 deletions

52
src/UnitJS/Async/Cache.js Normal file
View file

@ -0,0 +1,52 @@
function Cache(loader) {
this.loader = loader;
this.loaded = {};
this.loading = {};
}
Cache.prototype.get = function(key) {
return function(f) {
if(this.loaded[key] != undefined) {
f(this.loaded[key]);
} else {
this.startLoading(key);
this.loading[key].push(f);
this.loader(key)(this.store(key));
}
}.bind(this);
};
Cache.prototype.warmUp = function(key) {
if(this.loaded[key] == undefined) {
this.startLoading(key);
this.loader(key)(this.store(key));
}
};
Cache.prototype.startLoading = function(key) {
if(this.loading[key] == undefined) {
this.loading[key] = [];
}
};
Cache.prototype.store = function(key) {
return function(value) {
this.loaded[key] = value;
for(var i = 0; i < this.loading[key].length; i++) {
this.loading[key][i](value);
}
this.loading[key] = null;
}.bind(this);
};
return {
make: make
};
function make(loader) {
var cache = new Cache(loader);
return {
get: cache.get.bind(cache),
warmUp: cache.warmUp.bind(cache)
};
}

View file

@ -1,52 +1,3 @@
function Cache(loader) { import * as Cache from UnitJS.Async.Cache;
this.loader = loader;
this.loaded = {};
this.loading = {};
}
Cache.prototype.get = function(key) { return Cache; //Re-export for compatibility reasons
return function(f) {
if(this.loaded[key] != undefined) {
f(this.loaded[key]);
} else {
this.startLoading(key);
this.loading[key].push(f);
this.loader(key)(this.store(key));
}
}.bind(this);
};
Cache.prototype.warmUp = function(key) {
if(this.loaded[key] == undefined) {
this.startLoading(key);
this.loader(key)(this.store(key));
}
};
Cache.prototype.startLoading = function(key) {
if(this.loading[key] == undefined) {
this.loading[key] = [];
}
};
Cache.prototype.store = function(key) {
return function(value) {
this.loaded[key] = value;
for(var i = 0; i < this.loading[key].length; i++) {
this.loading[key][i](value);
}
this.loading[key] = null;
}.bind(this);
};
return {
make: make
};
function make(loader) {
var cache = new Cache(loader);
return {
get: cache.get.bind(cache),
warmUp: cache.warmUp.bind(cache)
};
}