Ox.api: cache sort; Ox.sortBy: improve performance

This commit is contained in:
rolux 2012-06-19 19:32:10 +02:00
parent 178e2bc487
commit 1f4b0f7faa

View file

@ -161,6 +161,7 @@ Ox.api = function(items, options) {
},
fn = function(options, callback) {
var data,
keys,
result = {data: {}, status: {code: 200, text: 'ok'}},
sort = {};
options = options || {};
@ -175,20 +176,29 @@ Ox.api = function(items, options) {
}
if (options.sort && result.data.items.length > 1) {
// sort
options.sort = parseSort(options.sort.concat(api.sort));
keys = [];
options.sort = parseSort(
options.sort.concat(api.sort)
).filter(function(v) {
var ret = keys.indexOf(v.key) == -1;
keys.push(v.key);
return ret;
});
options.sort.forEach(function(v) {
var key = v.key;
if (api.enums[key]) {
sort[key] = function(value) {
return api.enums[key].indexOf(value.toLowerCase());
};
} /*else if (Ox.isArray(items[0][key])) {
}/* else if (Ox.isArray(items[0][key])) {
sort[key] = function(value) {
return value.join(', ');
};
}*/
});
result.data.items = Ox.sortBy(result.data.items, options.sort, sort);
if (options.keys || options.positions) {
result.data.items = sortBy(result.data.items, options.sort, sort, options.query);
}
}
if (options.positions) {
// return positions
@ -268,7 +278,14 @@ Ox.api = function(items, options) {
}
callback && callback(result);
return result;
};
},
sortBy = Ox.cache(function sortBy(array, by, map, query) {
return Ox.sortBy(array, by, map);
}, {
key: function(args) {
return JSON.stringify([args[1], args[3]])
}
});
function parseEnums(enums) {
// make enumerable strings lowercase
@ -552,22 +569,17 @@ Ox.range = function() {
(function() {
function getSortValues(array, map) {
var mappedArray = map ? array.map(map) : array,
length, matches = [], sort = {};
// find numbers
var mappedArray = map ? array.map(map) : array, length = 0, sort = {};
// find numbers, and length of longest number
array.forEach(function(value, i) {
var match, mappedValue = mappedArray[i];
if (Ox.isString(mappedValue)) {
match = mappedValue.match(/\d+/g);
if (match) {
matches = matches.concat(match);
if (match && match.length > length) {
length = match.length;
}
}
});
// get length of longest number
length = Ox.max(Ox.map(matches, function(value) {
return value.length;
}));
// make lowercase, remove leading non-word characters,
// pad numbers and move leading articles to the end
array.forEach(function(value, i) {