Skip to content

Instantly share code, notes, and snippets.

@kocolosk
Created September 9, 2009 21:10
Show Gist options
  • Save kocolosk/184083 to your computer and use it in GitHub Desktop.
Save kocolosk/184083 to your computer and use it in GitHub Desktop.
reduce function to return a sorted array of the top 50 values
function(doc) {
emit(doc.parent_id, doc.visits);
}
function (keys, values, rereduce) {
var result = [];
var unique_keys = [];
function add_to_result(parent_id, visits) {
var index = unique_keys.indexOf(parent_id);
if (index == -1) {
unique_keys.push(parent_id);
result.push({"parent_id":parent_id, "visits":visits});
} else {
result[index].visits += visits;
}
}
function sort_result(a,b) {
if (a.visits < b.visits) return 1;
if (a.visits > b.visits) return -1;
return 0;
}
if (!rereduce) {
for (var i in keys) {
add_to_result(keys[i][0], values[i]);
}
}
else {
for each (var reduction in values) {
for each (var item in reduction) {
add_to_result(item.parent_id, item.visits);
}
}
}
return result.sort(sort_result).slice(0,50);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment