public
Last active

a CouchDB list function for returning the top Terms in where the key is like [Term|_Rest]

  • Download Gist
topN.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
function(seq, req) {
var min = 0, term, count, row
, i, top = parseInt(req.query.top), match = [];
while (row = getRow()) {
term = row.key[0];
count = row.value;
if (match.length < top) {
match.push([term, count]);
} else {
if (count > min) {
match = match.sort(function(a, b) {
return a[1] < b[1];
});
match.length = Math.min(match.length, top-1);
match.push([term, count]);
min = Infinity;
for (i=0; i < match.length; i++) {
if (match[i][1] < min) {
min = match[i][1];
}
};
}
}
}
match = match.sort(function(a, b) {
return a[1] < b[1];
});
return JSON.stringify(match.map(function(m) {return m[0];}));
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.