了解dc.js组减少方法

时间:2016-10-23 17:44:46

标签: javascript dc.js

我正在学习dc.js和javascript。并通过他们主页上的注释来源阅读:https://dc-js.github.io/dc.js/docs/stock.html。我不太明白这个特定的部分是如何工作的。

var ndx = crossfilter(data);
var all = ndx.groupAll();


var yearlyDimension = ndx.dimension(function (d) {
    return d3.time.year(d.dd).getFullYear();
});



     var yearlyPerformanceGroup = yearlyDimension.group().reduce(
    /* callback for when data is added to the current filter results */
    function (p, v) {
        ++p.count;
        p.absGain += v.close - v.open;
        p.fluctuation += Math.abs(v.close - v.open);
        p.sumIndex += (v.open + v.close) / 2;
        p.avgIndex = p.sumIndex / p.count;
        p.percentageGain = p.avgIndex ? (p.absGain / p.avgIndex) * 100 : 0;
        p.fluctuationPercentage = p.avgIndex ? (p.fluctuation / p.avgIndex) * 100 : 0;
        return p;
    },
    /* callback for when data is removed from the current filter results */
    function (p, v) {
        --p.count;
        p.absGain -= v.close - v.open;
        p.fluctuation -= Math.abs(v.close - v.open);
        p.sumIndex -= (v.open + v.close) / 2;
        p.avgIndex = p.count ? p.sumIndex / p.count : 0;
        p.percentageGain = p.avgIndex ? (p.absGain / p.avgIndex) * 100 : 0;
        p.fluctuationPercentage = p.avgIndex ? (p.fluctuation / p.avgIndex) * 100 : 0;
        return p;
    },
    /* initialize p */
    function () {
        return {
            count: 0,
            absGain: 0,
            fluctuation: 0,
            fluctuationPercentage: 0,
            sumIndex: 0,
            avgIndex: 0,
            percentageGain: 0
        };
    }
);

reduce方法似乎包含3个参数:( previous,current,initial)。

在这个特定的例子中,每个参数都传递了函数,但是这些函数中的每一个都有两个参数p和v ......究竟是什么传递给p和v?这个减少函数如何知道要调用哪一个?

0 个答案:

没有答案