From 1bfa11bb7ff4c37c54d6d9f140f0d031d80a88d0 Mon Sep 17 00:00:00 2001 From: Vjacheslav Trushkin Date: Thu, 11 Oct 2018 11:13:55 +0300 Subject: [PATCH] Cache collection data to reload same collections faster --- src/collection.js | 20 +++++++++++++++++++- src/collections.js | 3 ++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/collection.js b/src/collection.js index f2928d3..4e44ab9 100644 --- a/src/collection.js +++ b/src/collection.js @@ -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(); diff --git a/src/collections.js b/src/collections.js index 3e194d3..ea4677b 100644 --- a/src/collections.js +++ b/src/collections.js @@ -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);