Skip to content

Instantly share code, notes, and snippets.

@kris-ellery
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kris-ellery/11154574 to your computer and use it in GitHub Desktop.
Save kris-ellery/11154574 to your computer and use it in GitHub Desktop.
/**
* 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