I'm building a dc.js / d3.js dashboard in which I often have to make crossfilter groups containing a quantity for each key and a percentage of the total value for each key. That is why I want to make generic reduceAdd, reduceRemove and reduceInitial functions. I managed doing the first 2, but I don't understand reduceInitial behaviour :
function reduceAdd(dim,grouping,col) {
var keys = getKeys(dim); // get the keys name in an array of string
return function(p,v) {
p.total += parseInt(v[col]); // get the running total
for (var i = 0; i < keys.length; i++) {
if(v[grouping] == keys[i]) {p[keys[i]] += +v[col];}
p[keys[i]+"perc"] = p[keys[i]]/p.total; // calculate a percentage for ech key
}
return p;
}
}
function reduceRemove(dim,grouping,col) {
var keys = getKeys(dim);
return function(p,v) {
p.total -= parseInt(v[col]);
for (var i = 0; i < keys.length; i++) {
if(v[grouping] == keys[i]) {p[keys[i]] -= +v[col];}
p[keys[i]+"perc"] = p[keys[i]]/p.total;
}
return p;
}
}
This is the working non generic function reduceInitFC() {
return {total:0, LILOU:0, MARIUS:0,ORIANE:0,LILOUperc:0,MARIUSperc:0,ORIANEperc:0};
}
This is what I tried :
function reduceInit(dim) {
var keys = getKeys(dim);
var initArray= {};
initArray["total"] = 0;
for (var i = 0; i < keys.length; i++) {
initArray[keys[i]] = 0;
initArray[keys[i]+"perc"] = 0;
}
console.log(initArray); // (1)
console.log({total:0, LILOU:0, MARIUS:0,ORIANE:0,LILOUperc:0,MARIUSperc:0,ORIANEperc:0});
return function() {
return initArray;
}
}
The result is : (1) The output gives 0 for all the keys every two iterations and some non zero values for the other iterations When I use this function the resulting values in the group are constant respect with the keys what is not the case in reality and not the case when I hand write the zero values.
If anyone can help, it would be super kind and useful.
Best, Theo
getKeys
? Can you post a working example? I suspect that usinggetKeys
like this is causing bugs inreduceAdd
andreduceRemove
that you aren't realizing are there and that inreduceInit
there aren't yet any keys so you don't get any values, but it's impossible to tell without a working example where I can see whatgetKeys
does and exactly when the group is created.getKeys
introducing bugs. Though it won't update when new data is added, and that's actually good. If it did update you will have bugs. In any case, still need a working example in order to have much chance of diagnosing the problem.function getKeys(dim) { var len = dim.group().all().length; var keys = []; for (var i = 0; i < len; i++) { keys[i] = dim.group().all()[i].key; } return keys; }