Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions finance-tracker/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
7 changes: 7 additions & 0 deletions finance-tracker/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80
}
18 changes: 18 additions & 0 deletions finance-tracker/app.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
// This is the entrypoint for your application.
// node app.js
import { transactions } from './data.js';
import {
addTransaction,
getTotalIncome,
getTotalExpenses,
getBalance,
getTransactionsByCategory,
getLargestExpense,
printAllTransactions,
printSummary,
getAverageExpensePerCategory,
Comment on lines +5 to +13

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small suggestion 🙂

Some imported functions are not used in this file.
It’s best practice to remove unused imports to keep the code clean and easier to read.

} from './finance.js';

// Main execution
console.clear();
printAllTransactions(transactions);
printSummary(transactions);
getAverageExpensePerCategory(transactions);
// End of file
83 changes: 82 additions & 1 deletion finance-tracker/data.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,83 @@
// Place here the transaction data array. Use it in your application as needed.
const transactions = [];
export const transactions = [
{
id: 1,
type: 'income',
category: 'salary',
amount: 3000,
description: 'Monthly salary',
date: '2025-11-25',
},
{
id: 2,
type: 'expense',
category: 'groceries',
amount: 150.5,
description: 'Supermarket shopping',
date: '2025-12-05',
},
{
id: 3,
type: 'expense',
category: 'rent',
amount: 980,
description: 'Monthly rent',
date: '2025-12-01',
},
{
id: 4,
type: 'income',
category: 'freelance',
amount: 420,
description: 'Selling socks',
date: '2025-12-20',
},
{
id: 5,
type: 'expense',
category: 'utilities',
amount: 110.25,
description: 'Electricity and water',
date: '2025-12-15',
},
{
id: 6,
type: 'expense',
category: 'entertainment',
amount: 60,
description: 'Concert tickets',
date: '2025-12-27',
},
{
id: 7,
type: 'income',
category: 'investment',
amount: 150,
description: 'Stock market',
date: '2025-12-10',
},
{
id: 8,
type: 'expense',
category: 'transportation',
amount: 45,
description: 'Monthly bus pass',
date: '2025-11-03',
},
{
id: 9,
type: 'expense',
category: 'groceries',
amount: 95,
description: 'Weekly groceries',
date: '2025-11-10',
},
{
id: 10,
type: 'expense',
category: 'entertainment',
amount: 120,
description: 'New video game',
date: '2025-11-20',
},
];
144 changes: 130 additions & 14 deletions finance-tracker/finance.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,143 @@
function addTransaction(transaction) {
// TODO: Implement this function
import chalk from 'chalk';
import { transactions } from './data.js';

// Adds a new transaction to the transactions array
export function addTransaction(transaction) {
transactions.push(...[transaction]);
}

// Calculates and returns the total sum of all income transactions
export function getTotalIncome() {
let total = 0;
for (const transaction of transactions) {
if (transaction.type === 'income') {
total += transaction.amount;
}
}
return total;
}

function getTotalIncome() {
// TODO: Implement this function
// Calculates and returns the total sum of all expense transactions
export function getTotalExpenses() {
let total = 0;
for (const transaction of transactions) {
if (transaction.type === 'expense') {
total += transaction.amount;
}
}
return total;
}

function getTotalExpenses() {
// TODO: Implement this function
// Calculates and returns the balance (total income minus total expenses)
export function getBalance() {
return getTotalIncome() - getTotalExpenses();
}

function getBalance() {
// TODO: Implement this function
// Filters and returns all transactions that match a specific category
export function getTransactionsByCategory(transactions, category) {
const result = [];
for (const transaction of transactions) {
if (transaction.category === category) {
result.push(transaction);
}
}
return result;
}

function getTransactionsByCategory(category) {
// TODO: Implement this function
// Finds and returns the transaction object with the highest expense amount
export function getLargestExpense() {
let largestExpense = null;
let maxAmount = 0;
for (const transaction of transactions) {
if (transaction.type === 'expense' && transaction.amount > maxAmount) {
maxAmount = transaction.amount;
largestExpense = transaction;
}
}
return largestExpense;
}

function getLargestExpense() {
// TODO: Implement this function
// Displays all transactions in a formatted console output
export function printAllTransactions(transactions) {
console.log(chalk.bold.cyan('\n💰 PERSONAL FINANCE TRACKER 💰\n'));
console.log(chalk.bold('All Transactions:\n'));

transactions.forEach((transaction, index) => {
// destructuring
const { id, type, category, amount, description } = transaction;
const typeLabel = type === 'income' ? '[INCOME]' : '[EXPENSE]'; // createing type label
const coloredAmount =
type === 'income' ? chalk.green(`€${amount}`) : chalk.red(`€${amount}`); // green for income red for expense
const coloredCategory = chalk.yellow(`(${category})`); // yellow for category

console.log(
`${index + 1}. ${typeLabel} ${description} - ${coloredAmount} ${coloredCategory}`
); // output: 1. typeLabel description - €amount (category)
});
console.log(); // extra line for better readability
}

function printAllTransactions() {
// TODO: Implement this function
// Print summary of financial data
export function printSummary(transactions) {
const totalIncome = getTotalIncome(transactions);
const totalExpenses = getTotalExpenses(transactions);
const balance = getBalance(transactions);
const largestExpense = getLargestExpense(transactions);
const transactionCount = transactions.length;

console.log(chalk.bold.cyan('\n📊 FINANCIAL SUMMARY 📊\n'));

console.log(`Total Income: ${chalk.green(`€${totalIncome}`)}`);
console.log(`Total Expenses: ${chalk.red(`€${totalExpenses}`)}`);

// Balance color-coded based on positive or negative
const balanceColor = balance >= 0 ? chalk.cyan : chalk.red;
console.log(`Current Balance: ${balanceColor(`€${balance}`)}`);

if (largestExpense) {
console.log(
`\nLargest Expense: ${largestExpense.description} (${chalk.red(
`€${largestExpense.amount}`
)})`
);
}

console.log(`Total Transactions: ${chalk.bold(transactionCount)}\n`);
}

// Calculates and returns the average expense amount for each category
export function getAverageExpensePerCategory(transactions) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice implementation 👍.

const expenses = transactions.filter(
(transaction) => transaction.type === 'expense'
);
const categoryTotals = {};
const categoryCounts = {};
/**
* This loop iterates through each transaction in the `expenses` array.
* For each transaction, it updates two objects:
* 1. `categoryTotals`: It adds the transaction's `amount` to a running total for its specific `category`.
* If a category is seen for the first time, it's initialized to 0 before adding the amount.
* 2. `categoryCounts`: It increments a counter for the transaction's `category`.
* If a category is seen for the first time, its count is initialized to 0 before incrementing.
* This effectively calculates both the total amount spent and the number of transactions per category.
*/
for (const { category, amount } of expenses) {
categoryTotals[category] = (categoryTotals[category] || 0) + amount;
categoryCounts[category] = (categoryCounts[category] || 0) + 1;
}

const averages = {}; // storing average expense per category
for (const category in categoryTotals) {
const total = categoryTotals[category];
const count = categoryCounts[category];
averages[category] = +(total / count).toFixed(2); // Calculate average and round to 2 decimal places
}

console.log(chalk.bold('Average Expense per Category:'));
for (const category in averages) {
const average = averages[category];
console.log(`- ${category}: ${chalk.red(`€${average}`)}`);
}

return averages;
}
105 changes: 105 additions & 0 deletions finance-tracker/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading