Skip to content

Instantly share code, notes, and snippets.

@jchris
Created October 31, 2010 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jchris/656692 to your computer and use it in GitHub Desktop.
Save jchris/656692 to your computer and use it in GitHub Desktop.
a CouchDB list function for returning the top Terms in where the key is like [Term|_Rest]
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];}));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment