Debian Codegraph @

lib/order/sort.js

raw symbols SCIP
1 var _ = require("../lodash");
2 var util = require("../util");
3
4 module.exports = sort;
5
6 function sort(entries, biasRight) {
7 var parts = util.partition(entries, function(entry) {
8 return _.has(entry, "barycenter");
9 });
10 var sortable = parts.lhs,
11 unsortable = _.sortBy(parts.rhs, function(entry) { return -entry.i; }),
12 vs = [],
13 sum = 0,
14 weight = 0,
15 vsIndex = 0;
16
17 sortable.sort(compareWithBias(!!biasRight));
18
19 vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
20
21 _.forEach(sortable, function (entry) {
22 vsIndex += entry.vs.length;
23 vs.push(entry.vs);
24 sum += entry.barycenter * entry.weight;
25 weight += entry.weight;
26 vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
27 });
28
29 var result = { vs: _.flatten(vs, true) };
30 if (weight) {
31 result.barycenter = sum / weight;
32 result.weight = weight;
33 }
34 return result;
35 }
36
37 function consumeUnsortable(vs, unsortable, index) {
38 var last;
39 while (unsortable.length && (last = _.last(unsortable)).i <= index) {
40 unsortable.pop();
41 vs.push(last.vs);
42 index++;
43 }
44 return index;
45 }
46
47 function compareWithBias(bias) {
48 return function(entryV, entryW) {
49 if (entryV.barycenter < entryW.barycenter) {
50 return -1;
51 } else if (entryV.barycenter > entryW.barycenter) {
52 return 1;
53 }
54
55 return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
56 };
57 }