Last active
August 29, 2015 14:00
-
-
Save kris-ellery/11154574 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Total amount function using module pattern | |
*/ | |
var TotalAmount = (function () { | |
var amount = 0; | |
var api = {}; | |
function isNumber(n) { | |
return !isNaN(parseFloat(n)) && isFinite(n); | |
} | |
api.get = function () { | |
var parts = amount.toFixed(2).toString().split('.'); | |
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); | |
return '$' + parts.join('.'); | |
}; | |
api.increment = function (value) { | |
if (isNumber(value)) amount += value; | |
}; | |
api.decrement = function (value) { | |
if (isNumber(value)) amount -= value; | |
if (amount < 0) amount = 0; | |
}; | |
api.set = function (value) { | |
if (isNumber(value)) amount = value; | |
}; | |
api.reset = function () { | |
amount = 0; | |
}; | |
return api; | |
})(); | |
console.log(TotalAmount.get()); // $0.00 | |
TotalAmount.increment(329.99); | |
console.log(TotalAmount.get()); // $329.99 | |
TotalAmount.increment(999); | |
console.log(TotalAmount.get()); // $1,328.99 | |
TotalAmount.decrement(19.99); | |
console.log(TotalAmount.get()); // $1,309.00 | |
TotalAmount.reset(); | |
console.log(TotalAmount.get()); // $0.00 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment