需要制作定制的reducer来减去两个值

时间:2019-01-14 14:21:23

标签: dc.js crossfilter

"Date(UTC)","Market","Type","Price","Amount","Total","Fee","Fee Coin"
12:18:07","ETCBTC","BUY","0.002064","1.05","0.00216720","0.00105","ETC"
"2018-05-26 06:01:12","ETCBTC","SELL","0.00207","5.86","0.01213020","0.00001213","BTC"
"2018-05-25 22:47:14","ETCBTC","BUY","0.002","1.32","0.00264000","0.00132","ETC"

这是我的数据集的一部分。问题在于,在我的数据集中,我需要使用的“总计”仅仅是数字-为了使它们起作用,我必须将它们与“类型”(买/卖)连接起来。

买入应该像“-”一样工作,卖应该像“ +”一样工作;它们之间的区别在于我需要显示什么。

我正在学习。所以我没有尝试很多。

function show_profit(ndx) {
var typeDim = ndx.dimension(dc.pluck("Type"));
var profit = typeDim.group().reduce(
    function (p, v) {
        p.count++;
        p.total += v.Total;
        return p;
    },
    function (p, v) {
        p.count--;
        p.total -= v.Total;
        return p;
    },
    function () {
        return { count:0, total: 0};
    }
);

dc.barChart("#profit")
    .width(500)
    .height(300)
    .dimension(typeDim)
    .group(profit)
    .valueAccessor(function (d) {
        if (d.value.count == 0) {
            return 0;
        } else {
            return d.value.total;
        }
    })
    .transitionDuration(500)
    .x(d3.scale.ordinal())
    .xUnits(dc.units.ordinal)
    .elasticY(true)
    .xAxisLabel("Type")
    .yAxisLabel("Amount")
    .yAxis().ticks(20);
}

我只是用买入和卖出量绘制了图表。 我的目标是找出“买入”和“卖出”之间的差异并将其显示在折线图中。

1 个答案:

答案 0 :(得分:3)

我不确定我是否完全理解您的问题,但是如果您只是想将SELL设为正,将BUY设为负,则应该可以将值乘以1-1在您的归约函数中:

function mult(type) {
    switch(type) {
    case 'SELL': return 1;
    case 'BUY': return -1;
    default: throw new Error('unknown Type ' + type);
} 
var profit = typeDim.group().reduce(
    function (p, v) {
        p.count++;
        p.total += mult(v.Type) * v.Total;
        return p;
    },
    function (p, v) {
        p.count--;
        p.total -= mult(v.Type) * v.Total;
        return p;
    },
    function () {
        return { count:0, total: 0};
    }
);