NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

//Budget controller
var BudgetController = (function () {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;

this.calcPercentage = function(totalIncome) {
if (totalIncome > 0) {
this.percentage = Math.round((this.value / totalIncome) * 100);
} else {
this.percentage = -1;
}
};

this.getPercentage = function() {
return this.percentage;
};
};


var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};


var calculateTotal = function(type) {
var sum = 0;
data.allItems[type].forEach(function(cur) {
sum += cur.value;
});
data.totals[type] = sum;
};

var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};

return {
addItem: function(type, des, val) {
var newItem, ID;

var d = data.allItems[type]
// Create new ID
if (d.length > 0) {
ID = d[d.length - 1].id + 1;
} else {
ID = 0;
}

// Create new item based on 'inc' or 'exp' type
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}

// Push it into our data structure
d.push(newItem);

// Return the new element
return newItem;
},


calculateBudget: function() {
// calculate total income and expenses
calculateTotal('exp');
calculateTotal('inc');

// Calculate the budget: income - expenses
data.budget = data.totals.inc - data.totals.exp;

// calculate the percentage of income that we spent
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}

// Expense = 100 and income 300, spent 33.333% = 100/300 = 0.3333 * 100
},

calculatePercentages: function() {
data.allItems.exp.forEach(function(cur) {
cur.calcPercentage(data.totals.inc);
});
},


getPercentages: function() {
var allPerc = data.allItems.exp.map(function(cur) {
return cur.getPercentage();
});
return allPerc;
},


getBudget: function() {
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
};
}
};


})();


// UI CONTROLLER
var UIController = (function() {

var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container',
expensesPercLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};


var formatNumber = function(num, type) {
var numSplit, int, dec, type;

num = Math.abs(num);
num = num.toFixed(2);

numSplit = num.split('.');

int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}

dec = numSplit[1];

return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;

};


var nodeListForEach = function(list, callback) {
for (var i = 0; i < list.length; i++) {
callback(list[i], i);
}
};


return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value, // Will be either inc or exp
description: document.querySelector(DOMstrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMstrings.inputValue).value)
};
},


addListItem: function(obj, type) {
var html, newHtml, element;
// Create HTML string with placeholder text

if (type === 'inc') {
element = DOMstrings.incomeContainer;

html = '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp') {
element = DOMstrings.expensesContainer;

html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__ "><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}

// Replace the placeholder text with some actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value, type));

// Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},


clearFields: function() {
var fields, fieldsArr;

fields = document.querySelectorAll(DOMstrings.inputDescription + ', ' + DOMstrings.inputValue);

fieldsArr = Array.prototype.slice.call(fields);

fieldsArr.forEach(function(current, index, array) {
current.value = "";
});

fieldsArr[0].focus();
},


displayBudget: function(obj) {
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';

document.querySelector(DOMstrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMstrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMstrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp');

if (obj.percentage > 0) {
document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMstrings.percentageLabel).textContent = '---';
}

},


displayPercentages: function(percentages) {

var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);

nodeListForEach(fields, function(current, index) {

if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---';
}
});

},


displayMonth: function() {
var now, months, month, year;

now = new Date();
//var christmas = new Date(2016, 12, 25);

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
month = now.getMonth();

year = now.getFullYear();
document.querySelector(DOMstrings.dateLabel).textContent = months[month] + ' ' + year;
},


changedType: function() {

var fields = document.querySelectorAll(
DOMstrings.inputType + ',' +
DOMstrings.inputDescription + ',' +
DOMstrings.inputValue);

nodeListForEach(fields, function(cur) {
cur.classList.toggle('red-focus');
});

document.querySelector(DOMstrings.inputBtn).classList.toggle('red');

},

getDOMstrings: function() {
return DOMstrings;
}
};

})();

//App Controller
var AppController = (function(budgetCtrl, UICtrl) {

var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();

document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);

document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});

document.querySelector(DOM.inputType).addEventListener('change', UICtrl.changedType);
};


var updateBudget = function() {

// 1. Calculate the budget
budgetCtrl.calculateBudget();

// 2. Return the budget
var budget = budgetCtrl.getBudget();

// 3. Display the budget on the UI
UICtrl.displayBudget(budget);
};


var updatePercentages = function() {

// 1. Calculate percentages
budgetCtrl.calculatePercentages();

// 2. Read percentages from the budget controller
var percentages = budgetCtrl.getPercentages();

// 3. Update the UI with the new percentages
UICtrl.displayPercentages(percentages);
};


var ctrlAddItem = function() {
var input, newItem;

// 1. Get the field input data
input = UICtrl.getInput();

if (input.description !== "" && !isNaN(input.value) && input.value > 0) {
// 2. Add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);

// 3. Add the item to the UI
UICtrl.addListItem(newItem, input.type);

// 4. Clear the fields
UICtrl.clearFields();

// 5. Calculate and update budget
updateBudget();

// 6. Calculate and update percentages
updatePercentages();
}
};

return {
init: function() {
console.log('Application has started.');
UICtrl.displayMonth();
UICtrl.displayBudget({
budget: 0,
totalInc: 0,
totalExp: 0,
percentage: -1
});
setupEventListeners();
}
};

})(BudgetController, UIController);

AppController.init();

























     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.