Skip to content

Instantly share code, notes, and snippets.

@jchris
Created November 26, 2010 04:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchris/716288 to your computer and use it in GitHub Desktop.
Save jchris/716288 to your computer and use it in GitHub Desktop.
unique key count reduce
function(ks, vs, rr) {
// values are discarded by reduce
// todo: configurable key function, for complex queries
var fk, lk;
function uniqCount(keys) {
var count = 0, obj = {};
for (var i=0; i < keys.length; i++) {
if (!obj[keys[i]]) {
count++;
obj[keys[i]] = true;
}
};
return count;
};
if (rr) {
var fv = vs.shift()
, lv = vs.pop()
, count = fv[1] + lv[1]
, leftover_keys = [fv[2], lv[0]]
, v, i
;
fk = fv[0];
lk = lv[2];
for (i=0; i < vs.length; i++) {
v = vs[i];
count = count + v[1];
leftover_keys.push(v[0]);
leftover_keys.push(v[2]);
};
return [fk, uniqCount(leftover_keys) + count, lk];
} else {
fk = ks.shift();
lk = ks.pop();
return [fk, uniqCount(ks), lk];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment