Created
October 31, 2010 15:03
-
-
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]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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