2017-10-14 69 views
0

我有多個彙總使用相同的代碼,即:在d3彙總中重用匯總相關代碼的最優雅方式?

rolledUpData1 = d3.nest() 
       .key(function (d) { return d.city; }) 
       .rollup(function (values) { 
        return { 
         yearWeek: toYearWeek(values[0].date) + ' Mon', 
         mondayDate: parseYearWeek(toYearWeek(values[0].date) + ' Mon'), 
         totalRevenue: d3.sum(values, function (d) { return parseFloat(d.price) }), 
         }), // 
        } 
       }) 
       .entries(filteredData) 

和:

rolledUpData2 = d3.nest() 
       .key(function (d) { return d.store; }) 
       .rollup(function (values) { 
        return { 
         yearWeek: toYearWeek(values[0].date) + ' Mon', 
         mondayDate: parseYearWeek(toYearWeek(values[0].date) + ' Mon'), 
         totalRevenue: d3.sum(values, function (d) { return parseFloat(d.price) }), 
         }), // 
        } 
       }) 
       .entries(filteredData) 

什麼是每個彙總不重複的代碼的最優雅的方式?

     yearWeek: toYearWeek(values[0].date) + ' Mon', 
         mondayDate: parseYearWeek(toYearWeek(values[0].date) + ' Mon'), 
         totalRevenue: d3.sum(values, function (d) { return parseFloat(d.price) }), 

回答

0

最好的辦法是聲明函數:

function defaultRollup(values) { 
        return { 
         yearWeek: toYearWeek(values[0].date) + ' Mon', 
         mondayDate: parseYearWeek(toYearWeek(values[0].date) + ' Mon'), 
         totalRevenue: d3.sum(values, function (d) { return parseFloat(d.price) }), 
        } 
       } 

然後使用叫它

   .rollup(function(values) { return defaultRollup(values)})