I have a front end which has a table of orders. Each order may be delivered, not delivered or partially delivered. I need to calculate totals based on which option is selected (so total is filtered also), and I did come to a solution, but I know I am overcomplicating things, I am not really an AngularJS dev.
function calculateTotals(){
vm.sales.total_amount = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0};
vm.sales.total_price = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0};
vm.sales.order_total_price = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0};
vm.sales.order_total_amount = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0};
angular.forEach(vm.sales, function (sale) {
angular.forEach(vm.sales.total_amount, function(value, key){
vm.sales.total_amount[key] += (sale.status == key) ? sale.total_amount * 1 : 0;
vm.sales.total_price[key] += (sale.status == key) ? sale.total_price * 1 : 0;
vm.sales.order_total_amount[key] += (sale.status == key) ? sale.order_total_amount * 1 : 0;
vm.sales.order_total_price[key] += (sale.status == key) ? sale.order_total_price * 1 : 0;
});
vm.sales.total_amount['_'] += sale.total_amount * 1;
vm.sales.total_price['_'] += sale.total_price * 1;
vm.sales.order_total_amount['_'] += sale.order_total_amount * 1;
vm.sales.order_total_price['_'] += sale.order_total_price * 1;
});
vm.sales.total_amount['_'] = vm.sales.total_amount['_'] - vm.sales.total_amount['n-p'];
vm.sales.total_price['_'] = vm.sales.total_price['_'] - vm.sales.total_price['n-p'];
vm.sales.order_total_amount['_'] = vm.sales.order_total_amount['_'] - vm.sales.order_total_amount['n-p'];
vm.sales.order_total_price['_'] = vm.sales.order_total_price['_'] - vm.sales.order_total_price['n-p'];
}
There are 4 variables I need in front, total amount and total price (sum of many deliveries, coming summed up from the Laravel back end), order total price and order total amount (fetching from Laravel back end).
How can I simplify this?
EDIT thanks to stej4n I've came up to this...though I still feel it can go simpler
function calculateTotals() {
var properties = ['total_amount', 'total_price', 'order_total_amount', 'order_total_price'];
var keys = ['_', '_not', '_part', '_done', 'n-p'];
angular.forEach(properties, function (prop) {
vm.sales[prop] = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0};
});
angular.forEach(vm.sales, function (sale) {
angular.forEach(properties, function (prop) {
vm.sales[prop]['_'] += sale[prop] * 1;
angular.forEach(keys, function (key) {
vm.sales[prop][key] += (sale.status == key) ? sale[prop] * 1 : 0;
});
});
});
angular.forEach(properties, function (prop) {
vm.sales[prop]['_'] -= vm.sales[prop]['n-p'];
});
}