Skip to content

Commit 8a2292c

Browse files
committed
plotly#189 rewriting cateogory sorter to O(1) + one sort call
1 parent 7c355b8 commit 8a2292c

File tree

1 file changed

+24
-18
lines changed

1 file changed

+24
-18
lines changed

src/plots/cartesian/ordered_categories.js

+24-18
Original file line numberDiff line numberDiff line change
@@ -23,22 +23,28 @@ var d3 = require('d3');
2323
*/
2424
module.exports = function orderedCategories(axisLetter, categorymode, categorylist, data) {
2525

26-
return categorymode === 'array' ?
27-
28-
// just return a copy of the specified array ...
29-
(Array.isArray(categorylist) ? categorylist : []).slice() :
30-
31-
// ... or take the union of all encountered tick keys and sort them as specified
32-
// (could be simplified with lodash-fp or ramda)
33-
34-
['category ascending', 'category descending'].indexOf(categorymode) > -1 ?
35-
36-
[].concat.apply([], data.map(function(d) {return d[axisLetter];}))
37-
.filter(function(element, index, array) {return index === array.indexOf(element);})
38-
.sort(({
39-
'category ascending': d3.ascending,
40-
'category descending': d3.descending
41-
})[categorymode]) :
42-
43-
[].slice();
26+
if(categorymode === 'array') {
27+
// just return a copy of the specified array, if any
28+
return (Array.isArray(categorylist) ? categorylist : []).slice();
29+
} else if(['category ascending', 'category descending'].indexOf(categorymode) === -1) {
30+
return [].slice();
31+
} else {
32+
var traceLines = data.map(function(d) {return d[axisLetter];});
33+
var categoryMap = {}; // hashmap is O(1);
34+
var i, j, tracePoints, category;
35+
for(i = 0; i < traceLines.length; i++) {
36+
tracePoints = traceLines[i];
37+
for(j = 0; j < tracePoints.length; j++) {
38+
category = tracePoints[j];
39+
if(!categoryMap[category]) {
40+
categoryMap[category] = true;
41+
}
42+
}
43+
}
44+
return Object.keys(categoryMap)
45+
.sort(({
46+
'category ascending': d3.ascending,
47+
'category descending': d3.descending
48+
})[categorymode]);
49+
}
4450
};

0 commit comments

Comments
 (0)