From 1f4b0f7faab02a88630a2fbf9687c094297da045 Mon Sep 17 00:00:00 2001 From: rolux Date: Tue, 19 Jun 2012 19:32:10 +0200 Subject: [PATCH] Ox.api: cache sort; Ox.sortBy: improve performance --- source/Ox/js/Array.js | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/source/Ox/js/Array.js b/source/Ox/js/Array.js index bedecac8..88b810c6 100644 --- a/source/Ox/js/Array.js +++ b/source/Ox/js/Array.js @@ -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) {