Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 🎸 Total Accumulator hook for totals row #55

Merged
merged 7 commits into from
Feb 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,24 @@ <h1>Frappé DataTable</h1>
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);

Expand Down
33 changes: 23 additions & 10 deletions src/body-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';
}
Expand All @@ -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;
}

Expand Down
3 changes: 3 additions & 0 deletions src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export default {
onCheckRow(row) {},
onDestroy() {}
},
hooks: {
columnTotal: null
},
sortIndicator: {
asc: '↑',
desc: '↓',
Expand Down