cleanup filtering code in lanwchair dao

This commit is contained in:
Tankred Hase 2013-06-03 23:08:23 +02:00
parent 5e14aa0215
commit b580506465
1 changed files with 20 additions and 20 deletions

View File

@ -57,46 +57,46 @@ app.dao.LawnchairDAO = function(Lawnchair) {
* @param num [Number] The number of items to fetch (null means fetch all) * @param num [Number] The number of items to fetch (null means fetch all)
*/ */
this.list = function(type, offset, num, callback) { this.list = function(type, offset, num, callback) {
var i, list = [], var i, from, to,
matchingKeys = [], matchingKeys = [],
parts, timeStr, time; intervalKeys = [],
list = [];
// get all keys // get all keys
db.keys(function(keys) { db.keys(function(keys) {
// check if key begins with type // check if key begins with type
for (i = 0; i < keys.length; i++) { keys.forEach(function(key) {
if (keys[i].indexOf(type) === 0) { if (key.indexOf(type) === 0) {
matchingKeys.push(keys[i]); matchingKeys.push(key);
} }
} });
// sort keys // sort keys
matchingKeys.sort(); matchingKeys.sort();
// if num is null, list all items
num = (num !== null) ? num : matchingKeys.length;
// set window of items to fetch // set window of items to fetch
if (offset + num < matchingKeys.length) { // if num is null, list all items
matchingKeys = matchingKeys.splice(matchingKeys.length - offset - num, num); from = (num) ? matchingKeys.length - offset - num : 0;
} else if (offset + num >= matchingKeys.length && offset < matchingKeys.length) { to = matchingKeys.length - 1 - offset;
matchingKeys = matchingKeys.splice(0, matchingKeys.length - offset); // filter items within requested interval
} else { for (i = 0; i < matchingKeys.length; i++) {
matchingKeys = []; if (i >= from && i <= to) {
intervalKeys.push(matchingKeys[i]);
}
} }
// return if there are no matching keys // return if there are no matching keys
if (matchingKeys.length === 0) { if (intervalKeys.length === 0) {
callback(list); callback(list);
return; return;
} }
// fetch all items from data-store with matching key // fetch all items from data-store with matching key
db.get(matchingKeys, function(matchingList) { db.get(intervalKeys, function(intervalList) {
for (i = 0; i < matchingList.length; i++) { intervalList.forEach(function(item) {
list.push(matchingList[i].object); list.push(item.object);
} });
// return only the interval between offset and num // return only the interval between offset and num
callback(list); callback(list);