reductio
Version:
Reductio: Crossfilter groupings
88 lines (75 loc) • 2.38 kB
JavaScript
import build from './build.js';
import accessors from './accessors.js';
import params from './parameters.js';
import postprocess from './postprocess';
import postprocessors from './postprocessors';
import crossfilter from 'crossfilter2';
function reductio() {
var parameters = params();
var funcs = {};
function my(group) {
// Start fresh each time.
funcs = {
reduceAdd: function(p) { return p; },
reduceRemove: function(p) { return p; },
reduceInitial: function () { return {}; },
};
build.build(parameters, funcs);
// If we're doing groupAll
if(parameters.groupAll) {
if(group.top) {
console.warn("'groupAll' is defined but attempting to run on a standard dimension.group(). Must run on dimension.groupAll().");
} else {
var bisect = crossfilter.bisect.by(function(d) { return d.key; }).left;
var i, j;
var keys;
var keysLength;
var k; // Key
group.reduce(
function(p, v, nf) {
keys = parameters.groupAll(v);
keysLength = keys.length;
for(j=0;j<keysLength;j++) {
k = keys[j];
i = bisect(p, k, 0, p.length);
if(!p[i] || p[i].key !== k) {
// If the group doesn't yet exist, create it first.
p.splice(i, 0, { key: k, value: funcs.reduceInitial() });
}
// Then pass the record and the group value to the reducers
funcs.reduceAdd(p[i].value, v, nf);
}
return p;
},
function(p, v, nf) {
keys = parameters.groupAll(v);
keysLength = keys.length;
for(j=0;j<keysLength;j++) {
i = bisect(p, keys[j], 0, p.length);
// The group should exist or we're in trouble!
// Then pass the record and the group value to the reducers
funcs.reduceRemove(p[i].value, v, nf);
}
return p;
},
function() {
return [];
}
);
if(!group.all) {
// Add an 'all' method for compatibility with standard Crossfilter groups.
group.all = function() { return this.value(); };
}
}
} else {
group.reduce(funcs.reduceAdd, funcs.reduceRemove, funcs.reduceInitial);
}
postprocessed(group, parameters, funcs);
return group;
}
accessors.build(my, parameters);
return my;
}
postprocessors(reductio);
const postprocessed = postprocess(reductio);
export default reductio;