diff --git a/projects/001-budget-app/js/index.js b/projects/001-budget-app/js/index.js index e69de29..a4d9096 100644 --- a/projects/001-budget-app/js/index.js +++ b/projects/001-budget-app/js/index.js @@ -0,0 +1,171 @@ +/** Class representing a Category. */ +class Category { + /** + * Creates a category and assigns it the name and an empty array, the ledger, which will be populated later by the history of the movement of money. + * @param {string} category - The name of the category + */ + constructor(category){ + this.categoryName = category; + this.ledger = []; + } + /** + * Appends a deposit to the ledger list reporting the amount and the description + * @param {number} amount - The amount to be deposited + * @param {string} description - The description of the deposit + */ + deposit(amount, description = ''){ + this.ledger.push({ + amount: amount, + description: description + }); + } + /** + * Appends a withdrawal to the ledger list reporting the negative amount and the description + * @param {number} amount - The amount to be withdrawn + * @param {string} description - The description of the withdrawal + * @returns {boolean} `true` if the balance is positive and the amount to be withdrawn does not make it negative, otherwise `false` + */ + withdraw(amount, description = ''){ + if(this.checkFunds(amount)){ + this.ledger.push({ + amount: -amount, + description: description + }); + return true; + } + + return false; + } + /** + * Returns the current balance of the budget category based on the deposits and withdrawals that have occurred + * @returns {number} The balance + */ + getBalance(){ + return this.ledger.reduce((totalBalance, transaction) => totalBalance + parseFloat(transaction.amount), 0); + } + /** + * Returns the current balance of the budget category based only on the withdrawals that have occurred + * @returns {number} The balance + */ + getWithdrawBalance(){ + // more performant code + // return this.ledger.reduce((totalBalance, transaction) => transaction.amount < 0 ? totalBalance + parseFloat(transaction.amount) : 0, 0); + // just for education + return this.ledger + .filter(transaction => transaction.amount < 0) + .reduce((totalBalance, transaction) => totalBalance + parseFloat(transaction.amount), 0); + } + /** + * Transfers an amount from a category to another and reports it int the ledger + * @param {*} amount - The amount to be transferred + * @param {*} budgetCategory - The category to which the transfer is made + * @returns {boolean} `true` if the balance is positive and the amount to be transferred does not make it negative, otherwise `false` + */ + transfer(amount, budgetCategory){ + if(this.checkFunds(amount)){ + this.withdraw(amount, `Transfer to ${budgetCategory.categoryName}`); + budgetCategory.deposit(amount, `Transfer from ${this.categoryName}`); + return true; + } + + return false; + } + /** + * Checks if the amount is greater than the balance of the budget category + * @param {*} amount - The amount to be checked + * @returns {boolean} `false` if the amount is greater than the balance of the budget category, otherwise `true` + */ + checkFunds(amount){ + if(amount > this.getBalance()) + return false; + + return true; + } + /** + * A static method that returns the relevant data of the category, i.e.: the name, the ledger movements and the balance + * @param {Category} category - The category to be processed + * @returns {string} The relevant data of the category + */ + static str(category){ + const asterisksLength = Math.floor((30 - category.categoryName.length) / 2); + let text = '*'.repeat(asterisksLength) + category.categoryName + '*'.repeat(asterisksLength + (category.categoryName.length % 2 === 0 ? 0 : 1)); + category.ledger.forEach(row => { + const amount = row.amount.toFixed(2); + const description = row.description.substring(0,23); + text += '\n' + description + ' '.repeat(30 - description.length - amount.length) + amount; + }); + + return `${text}\nTotal: ${category.getBalance(category)}`; + } +} +/** + * Returns the percentage spent in each category passed in to the function representing the data as a chart + * @param {Array} categories - The categories to be processed + * @returns {string} The resulting chart + */ +function createSpendChart(categories){ + let text = 'Percentage spent by category'; + const percentagesInTens = []; + + for (let i = 100; i >= 0; i=i-10) { + percentagesInTens.push(i) + } + + let totalWithdraw = 0; + let longestCategoryName = ''; + + const categoriesExtractedData = categories.map(category => { + const withdraw = category.getWithdrawBalance(); + + totalWithdraw += withdraw; + + if(category.categoryName.length > longestCategoryName.length){ + longestCategoryName = category.categoryName; + } + + return { + name: category.categoryName, + withdraw + } + }); + + let percentages = ''; + + percentagesInTens.forEach(percentage => { + percentages += '\n' + String(percentage).padStart(3, ' ') + '| '; + + categoriesExtractedData.forEach(category => { + const withdrawPercentage = Math.floor((category.withdraw / totalWithdraw) * 100); + + if(percentage <= withdrawPercentage){ + percentages += 'o '; + } else { + percentages += ' '; + } + }); + }); + + let dashes = `\n${' '.repeat(4)}${'-'.repeat(categoriesExtractedData.length*3 + 1)}`; + + let categoriesNames = ''; + + for (let i = 0; i < longestCategoryName.length; i++) { + categoriesNames += `\n${' '.repeat(5)}`; + categoriesExtractedData.forEach(category => { + if(typeof category.name[i] === 'undefined'){ + categoriesNames += ' '.repeat(3); + } else { + categoriesNames += `${category.name[i]} `; + } + }); + + } + + return text + percentages + dashes + categoriesNames; +} + +module.exports = { // For CommonJS environment +// export { // For ES module environment. In addition for Visual Studio Code two package.json files must be created, one in this file folder, the other one in the application file folder, they must contain the following code { "type": "module" } + Category, + createSpendChart +}; \ No newline at end of file diff --git a/projects/001-budget-app/js/index.test.js b/projects/001-budget-app/js/index.test.js new file mode 100644 index 0000000..9468156 --- /dev/null +++ b/projects/001-budget-app/js/index.test.js @@ -0,0 +1,142 @@ +const { + Category, + createSpendChart +} = require( './index.js' ); // For CommonJS environment + +let food, entertainment, business; + +beforeEach(() => { + food = new Category("Food"); + entertainment = new Category("Entertainment"); + business = new Category("Business"); +}); + +test('Expected `deposit` method to create a specific object in the ledger instance variable.', () => { + food.deposit(900, "deposit"); + const actual = food.ledger[0]; + const expected = { amount: 900, description: "deposit" }; + expect(actual).toEqual(expected); +}); + +test('Expected calling `deposit` method with no description to create a blank description.', () => { + food.deposit(45.56); + const actual = food.ledger[0]; + const expected = {amount: 45.56, description: ""}; + expect(actual).toEqual(expected); +}); + +describe('Expected `withdraw` method ', () => { + let good_withdraw, actual, expected; + + beforeEach(() => { + food.deposit(900, "deposit"); + good_withdraw = food.withdraw(45.67) + actual = food.ledger[1]; + expected = {amount: -45.67, description: ""}; + }); + + test('with no description to create a blank description.', () => { + + expect(actual).toEqual(expected); + }); + + test('to return `true`.', () => { + expect(good_withdraw).toEqual(true); + }); +}); + +test('Expected balance to be 854.33', () => { + food.deposit(900, "deposit"); + food.withdraw(45.67, "milk, cereal, eggs, bacon, bread"); + const actual = food.getBalance(); + const expected = 854.33; + expect(actual).toEqual(expected); +}); + +describe('Expected `transfer` method to ', () => { + let good_transfer, actual, expected; + + beforeEach(() => { + food.deposit(900, "deposit") + food.withdraw(45.67, "milk, cereal, eggs, bacon, bread") + good_transfer = food.transfer(20, entertainment) + actual = food.ledger[2] + expected = {amount: -20, description: "Transfer to Entertainment"} + }); + + test('create a specific ledger item in food object.', () => { + expect(actual).toEqual(expected); + }); + + test('return `true`.', () => { + expect(good_transfer).toBe(true); + }); + + test('create a specific ledger item in entertainment object.', () => { + actual = entertainment.ledger[0]; + expected = {amount: 20, description: "Transfer from Food"}; + expect(actual).toEqual(expected); + }); +}); + +describe('Expected `checkFunds` method to be ', () => { + let actual, expected; + + beforeEach(() => { + food.deposit(10, "deposit"); + }); + + test('return `false`.', () => { + actual = food.checkFunds(20); + expected = false; + expect(actual).toBe(expected); + }); + + test('return `true`.', () => { + actual = food.checkFunds(10); + expected = true; + expect(actual).toBe(expected); + }); +}); + +test('Expected `withdraw` method to return `false`.', () => { + food.deposit(100, "deposit"); + const good_withdraw = food.withdraw(100.10); + expect(good_withdraw).toBe(false); +}); + +test('Expected `transfer` method to return `false`.', () => { + food.deposit(100, "deposit"); + const good_transfer = food.transfer(200, entertainment); + expect(good_transfer).toBe(false); +}); + +test('Expected different string representation of object.', () => { + food.deposit(900, "deposit"); + food.withdraw(45.67, "milk, cereal, eggs, bacon, bread"); + food.transfer(20, entertainment); + const actual = Category.str(food); + const expected = `*************Food*************\ndeposit 900.00\nmilk, cereal, eggs, bac -45.67\nTransfer to Entertainme -20.00\nTotal: 834.33`; + expect(actual).toEqual(expected); +}); + +test('Expected different chart representation. Check that all spacing is exact.', () => { + food.deposit(900, "deposit"); + entertainment.deposit(900, "deposit"); + business.deposit(900, "deposit"); + food.withdraw(105.55); + entertainment.withdraw(33.40); + business.withdraw(10.99); + const actual = createSpendChart([business, food, entertainment]); + const expected = "Percentage spent by category\n100| \n 90| \n 80| \n 70| o \n 60| o \n 50| o \n 40| o \n 30| o \n 20| o o \n 10| o o \n 0| o o o \n ----------\n B F E \n u o n \n s o t \n i d e \n n r \n e t \n s a \n s i \n n \n m \n e \n n \n t "; + expect(actual).toEqual(expected); +}); + +test('Expected different string representation of object with a name made up of odd letters.', () => { + entertainment.deposit(900, "deposit"); + entertainment.withdraw(20.67, "movie, music"); + entertainment.transfer(50, food); + const actual = Category.str(entertainment); + const expected = `********Entertainment*********\ndeposit 900.00\nmovie, music -20.67\nTransfer to Food -50.00\nTotal: 829.33`; + expect(actual).toEqual(expected); +}); \ No newline at end of file