phpsmarter
1/16/2018 - 9:08 AM

ramda program

ramda program

    var byMonth = R.groupBy(R.prop('Month'));
    var byAuthor = R.groupBy(R.prop('Author'));

    var royalty_key = 'Royalty (SUM)';

    var months_keys = R.uniq(R.map(R.prop('Month'), data)).sort();
    var monthly_revenue =
        R.map((group) => 
            R.reduce((acc, record) => acc + parseMoney(record[royalty_key]), 0, group),
        byMonth(data));
    
    monthly_revenue = R.pickAll(months_keys, monthly_revenue); // sort by months_keys
    monthly_revenue = R.map(R.invoker(1, 'toFixed')(2), monthly_revenue);

    var data_by_month_keys = 
        R.map((data_by_authors) => 
            R.flatten(R.map((month) => 
                R.filter((record) => record.Month == month, data_by_authors),
            months_keys)),
        byAuthor(data));

    var authors = R.keys(data_by_month_keys);

    var reduceToUsageBy = R.reduceBy((acc, record) => 
        acc + parseUsage(record['PaidUsageInSeconds (SUM)']), 0);
    var usageByMonth = reduceToUsageBy((record) => record.Month);
    
    var usage_data = R.map((data_by_authors) => usageByMonth(data_by_authors), data_by_month_keys);
    
    var mergeAuthorNameKeys = R.compose(R.values, R.mapObjIndexed(R.flip(R.assoc('AuthorName'))));

    usage_data = mergeAuthorNameKeys(usage_data);

    monthly_revenue = Object.assign({}, {AuthorName: "Total Month"}, monthly_revenue);

    var data = R.concat(usage_data, [monthly_revenue]);