Cache collection data to reload same collections faster

This commit is contained in:
Vjacheslav Trushkin 2018-10-11 11:13:55 +03:00
parent ad3fc6a1c8
commit 1bfa11bb7f
2 changed files with 21 additions and 2 deletions

View File

@ -12,6 +12,8 @@ const defaultAttributes = {
vFlip: false
};
let cache = {};
/**
* Class to represent one collection of icons
*/
@ -119,17 +121,33 @@ class Collection {
* Load collection from file
*
* @param {string} file File or JSON
* @param {string} [defaultPrefix]
* @returns {Promise}
*/
loadFile(file) {
loadFile(file, defaultPrefix) {
return new Promise((fulfill, reject) => {
// Load file
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
let checkCache = typeof defaultPrefix === 'string';
// Check cache
if (checkCache && cache[defaultPrefix] !== void 0 && cache[defaultPrefix].length === file.length) {
// If JSON file has same length, assume its the same file. Do not bother with hashing
fulfill(cache[defaultPrefix].collection);
return;
}
this.loadJSON(data);
if (this.loaded) {
if (checkCache) {
cache[defaultPrefix] = {
length: file.length,
collection: this
};
}
fulfill(this);
} else {
reject();

View File

@ -240,7 +240,8 @@ class Collections {
collection = new Collection(prefix);
collection.repo = repo;
collection.loadFile(filename).then(() => {
collection.loadFile(filename, prefix).then(result => {
collection = result;
if (!collection.loaded) {
if (this._log !== null) {
this._log('Failed to loadQueue collection: ' + filename);