"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var helper_1 = require("../helper"); var partition_1 = require("../util/partition"); var simple_statistics_1 = require("simple-statistics"); function percent(rows, options) { var e_1, _a, e_2, _b; var opts = helper_1.mergeOptions(options, { as: 'percent', method: 'sum' }); var dimension = options.dimension, groupBy = options.groupBy, field = options.field, method = options.method; if (method === 'sum' && typeof field !== 'string') { throw new TypeError('Invalid field: must be a string!'); } if (typeof dimension !== 'string') { throw new TypeError('Invalid dimension: must be a string!'); } if (typeof opts.as !== 'string') { throw new TypeError('Invalid as: must be a string!'); } var result = []; var groups = partition_1.partition(rows, groupBy); try { for (var _c = tslib_1.__values(Object.values(groups)), _d = _c.next(); !_d.done; _d = _c.next()) { var group = _d.value; var totalSum = method === 'count' ? group.length : simple_statistics_1.sum(group.map(function (row) { return row[field]; })); if (totalSum === 0) { console.warn("Invalid data: total sum of field " + field + " is 0!"); } var innerGroups = partition_1.partition(group, dimension); try { for (var _e = (e_2 = void 0, tslib_1.__values(Object.values(innerGroups))), _f = _e.next(); !_f.done; _f = _e.next()) { var innerGroup = _f.value; var innerSum = method === 'count' ? innerGroup.length : simple_statistics_1.sum(innerGroup.map(function (row) { return row[field]; })); // const resultRow = pick(innerGroup[0], union(groupBy, [ dimension ])); var resultRow = tslib_1.__assign({}, innerGroup[0]); // FIXME in case dimension and field is the same // const dimensionValue = resultRow[dimension]; resultRow[field] = innerSum; // resultRow[dimension] = dimensionValue; if (totalSum === 0) { resultRow[opts.as] = 0; } else { resultRow[opts.as] = innerSum / totalSum; } result.push(resultRow); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_f && !_f.done && (_b = _e.return)) _b.call(_e); } finally { if (e_2) throw e_2.error; } } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_1) throw e_1.error; } } return result; } exports.percent = percent;