diff --git a/index.html b/index.html
index 5c04f2d..ec66ca4 100644
--- a/index.html
+++ b/index.html
@@ -216,7 +216,24 @@
Frappé DataTable
return format($input.value);
}
}
- }
+ },
+ hooks: {
+ columnTotal(columnValues, cell) {
+ if (cell.colIndex === 5) {
+ // calculated average for 5th column
+ const sum = columnValues.reduce((acc, value) => {
+ if (typeof value === 'number') {
+ return acc + value
+ }
+ return acc
+ }, 0);
+ return sum / columnValues.length
+ }
+ if (cell.colIndex === 2) {
+ return 'Total'
+ }
+ }
+ }
});
console.log(performance.now() - start);
diff --git a/src/body-renderer.js b/src/body-renderer.js
index 1c180c9..b635fc3 100644
--- a/src/body-renderer.js
+++ b/src/body-renderer.js
@@ -71,7 +71,7 @@ export default class BodyRenderer {
getTotalRow() {
const columns = this.datamanager.getColumns();
const totalRowTemplate = columns.map(col => {
- let content = 0;
+ let content = null;
if (['_rowIndex', '_checkbox'].includes(col.id)) {
content = '';
}
@@ -82,18 +82,31 @@ export default class BodyRenderer {
column: col
};
});
- const totalRow = this.visibleRows.reduce((acc, prevRow) => {
- return acc.map((cell, i) => {
+
+ const totalRow = totalRowTemplate.map((cell, i) => {
+ if (cell.content === '') return cell;
+
+ if (this.options.hooks.columnTotal) {
+ const columnValues = this.visibleRows.map(row => row[i].content);
+ const result = this.options.hooks.columnTotal.call(this.instance, columnValues, cell);
+ if (result != null) {
+ cell.content = result;
+ return cell;
+ }
+ }
+
+ cell.content = this.visibleRows.reduce((acc, prevRow) => {
const prevCell = prevRow[i];
if (typeof prevCell.content === 'number') {
- cell.content += prevRow[i].content;
+ if (acc == null) acc = 0;
+ return acc + prevCell.content;
}
- if (!cell.format && prevCell.format) {
- cell.format = prevCell.format;
- }
- return Object.assign({}, cell);
- });
- }, totalRowTemplate);
+ return acc;
+ }, cell.content);
+
+ return cell;
+ });
+
return totalRow;
}
diff --git a/src/defaults.js b/src/defaults.js
index e404905..af0396c 100644
--- a/src/defaults.js
+++ b/src/defaults.js
@@ -38,6 +38,9 @@ export default {
onCheckRow(row) {},
onDestroy() {}
},
+ hooks: {
+ columnTotal: null
+ },
sortIndicator: {
asc: '↑',
desc: '↓',