From 1d70af0e86e6f1923d3edca899f1814dcc299f4a Mon Sep 17 00:00:00 2001 From: haad Date: Tue, 23 Feb 2016 09:37:15 +0200 Subject: [PATCH] Fix stack overflow, refactor _fetchOne --- src/DataStore.js | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/DataStore.js b/src/DataStore.js index 3a73721..586bf7c 100644 --- a/src/DataStore.js +++ b/src/DataStore.js @@ -30,16 +30,6 @@ class DataStore { return this._fetchRecursive(options); } - _fetchOne(index) { - const item = this.list.items[this.list.items.length - index - 1]; - if(item) { - await(item.getPayload()); - const f = item.compact(); - return { hash: f.data, payload: f.Payload }; - } - return null; - } - _fetchRecursive(options, currentAmount, deleted, res) { const opts = { amount: options && options.amount ? options.amount : DefaultAmount, @@ -48,12 +38,18 @@ class DataStore { key: options && options.key ? options.key : null }; - let result = res ? res : []; - let handledItems = deleted ? deleted : []; - if(!currentAmount) currentAmount = 0; - const item = this._fetchOne(currentAmount); + if(!opts.first && !opts.last && !opts.key && opts.amount == -1) + return this.list.items.map(this._fetchOne).reverse(); + + let result = res ? res : []; + let handledItems = deleted ? deleted : []; + let item; + + const node = this.list.items[this.list.items.length - currentAmount - 1]; + if(node) + item = await(this._fetchOne(node)); if(item && item.payload) { const wasHandled = _.includes(handledItems, item.payload.key); @@ -89,6 +85,15 @@ class DataStore { return result; } + + _fetchOne(item) { + return new Promise((resolve, reject) => { + await(item.getPayload()); + const f = item.compact(); + const res = { hash: f.data, payload: f.Payload }; + resolve(res); + }); + } } module.exports = DataStore;