My intention is to create a nice DRY method (add
) which will take care of parsing floats and adding totals internally and will be called by other methods.
I feel like I'm jumping through unnecessary complex hoops here. Can anyone help me out?
PS: the intention is to be able to specify different objects with add, so if I had a label object called 'food' with a credit property I could create a function called addFoodCredit(amount)
which would call add( amount, 'credit', 'labels', 'food')
.
The full code can be seen here.
var dateObject = function() {
var totals = {
totalDebit: 0,
totalCredit: 0,
labels: {}
}
var add = function add( amount ) {
var args = Array.prototype.slice.call(arguments)
var objectReference = totals;
var floatAmount = parseFloat (args.shift());
var objectKey = args.shift();
while(args.length > 0) {
objectReference = objectReference[args.shift()];
}
var currentTotal = parseFloat( objectReference[objectKey] );
objectReference[objectKey] = currentTotal + floatAmount;
console.log(objectReference, objectKey);
console.log(totals.totalDebit)
};
this.addCredit = function addCredit( amount ) {
add( amount, 'totalCredit' );
};
this.addDebit = function addDebit ( amount ) {
add( amount, 'totalDebit');
};
this.addLabel = function ( label, amount, type ) {
var labelName = label + '-' + type;
if ( ! totals.labels.labelName ) {
totals.labels[labelName] = 0;
}
add(amount, labelName, 'labels')
}
this.print = function() {console.log(totals)};
};
var x = new dateObject();
x.addCredit(15);
x.addCredit(21);
x.addDebit(12.42);
x.addDebit(122);
x.addLabel('food', 20, 'dr')
x.print();