generated from HackYourFuture/core-assignment-week-4
-
Notifications
You must be signed in to change notification settings - Fork 19
Halyna R. #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
halyna1995
wants to merge
2
commits into
HackYourAssignment:main
Choose a base branch
from
halyna1995:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Halyna R. #5
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| node_modules |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| { | ||
| "semi": true, | ||
| "singleQuote": false, | ||
| "tabWidth": 2 | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,45 @@ | ||
| // This is the entrypoint for your application. | ||
| // node app.js | ||
| // app.js | ||
| import {printAllTransactions, addTransaction, getTransactionsByCategory, getTransactionsByDateRange, groupTransactionsByMonth, getAverageExpensePerCategory, removeTransactionById, findConsecutiveExpensiveMonths,} from "./finance.js"; | ||
|
|
||
| // Print data | ||
| printAllTransactions(); | ||
|
|
||
| // Add one transaction | ||
| addTransaction({ | ||
| id: 6, | ||
| type: "expense", | ||
| category: "transport", | ||
| amount: 60, | ||
| description: "Train ticket", | ||
| date: "2026-02-02", | ||
| }); | ||
|
|
||
| console.log("\nAfter adding one transaction:\n"); | ||
| printAllTransactions(); | ||
|
|
||
| // Filter by category | ||
| const foodTransactions = getTransactionsByCategory("food"); | ||
| console.log("\nFood transactions:", foodTransactions); | ||
|
|
||
| //Bonus Challenges | ||
| // Search transactions by date range using slice | ||
| const februaryRange = getTransactionsByDateRange("2026-02-02", "2026-02-04"); | ||
| console.log("\nDate range 2026-02-02..2026-02-04:", februaryRange); | ||
|
|
||
| // Group transactions by month using nested objects | ||
| const groupedByMonth = groupTransactionsByMonth(); | ||
| console.log("\nGrouped by month:", groupedByMonth); | ||
|
|
||
| // Calculate average expense per category | ||
| const average = getAverageExpensePerCategory(); | ||
| console.log("\nAverage expense per category:", average); | ||
|
|
||
| // Add ability to remove transactions by id | ||
| const removedById = removeTransactionById(2); | ||
| console.log("\nRemoved transaction with id=2:", removedById); | ||
|
|
||
| // Create a function that finds consecutive expensive months | ||
| const sequences = findConsecutiveExpensiveMonths(500); | ||
| console.log("\nConsecutive expensive months (>= 500):", sequences); |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,43 @@ | ||
| // 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: "2026-01-26", | ||
| }, | ||
| { | ||
| id: 2, | ||
| type: "expense", | ||
| category: "food", | ||
| amount: 400, | ||
| description: "Groceries", | ||
| date: "2026-01-28", | ||
| }, | ||
| { | ||
| id: 3, | ||
| type: "expense", | ||
| category: "housing", | ||
| amount: 1300, | ||
| description: "Rent", | ||
| date: "2026-01-27", | ||
| }, | ||
| { | ||
| id: 4, | ||
| type: "income", | ||
| category: "side-income", | ||
| amount: 600, | ||
| description: "Freelance", | ||
| date: "2026-01-29", | ||
| }, | ||
| { | ||
| id: 5, | ||
| type: "expense", | ||
| category: "bills", | ||
| amount: 250, | ||
| description: "Utilities", | ||
| date: "2026-01-30", | ||
| }, | ||
| ]; |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,258 @@ | ||
| function addTransaction(transaction) { | ||
| // TODO: Implement this function | ||
| // finance.js | ||
| import chalk from "chalk"; | ||
| import { transactions } from "./data.js"; | ||
|
|
||
| // Format number | ||
| function formatEUR(amount) { | ||
| return `€${amount}`; | ||
| } | ||
|
|
||
| /* | ||
| 1) addTransaction - Add new transaction to array | ||
| - Uses destructuring | ||
| - Uses spread operator when pushing | ||
| */ | ||
| export function addTransaction(transaction) { | ||
| const { id, type, category, amount, description, date } = transaction; | ||
| if ( id == null || !type || !category || amount == null || !description || !date ) { | ||
| console.log(chalk.red("❌ Missing required fields")); | ||
| return false; | ||
| } | ||
| transactions.push({ ...transaction }); | ||
| return true; | ||
| } | ||
|
|
||
| /* | ||
| 2) getTotalIncome() | ||
| - Sum income using a loop | ||
| */ | ||
| export function getTotalIncome() { | ||
| let sum = 0; | ||
| for (const transaction of transactions) { | ||
| if (transaction.type === "income") { | ||
| sum += transaction.amount; | ||
| } | ||
| } | ||
| return sum; | ||
| } | ||
|
|
||
| /* | ||
| 3) getTotalExpenses() | ||
| - Sum expenses using a loop | ||
| */ | ||
| export function getTotalExpenses() { | ||
| let sum = 0; | ||
| for (const transaction of transactions) { | ||
| if (transaction.type === "expense") { | ||
| sum = sum + transaction.amount; | ||
| } | ||
| } | ||
| return sum; | ||
| } | ||
|
|
||
| /* | ||
| 4) getBalance() - Calculate total income minus expenses | ||
| */ | ||
| export function getBalance() { | ||
| return getTotalIncome() - getTotalExpenses(); | ||
| } | ||
|
|
||
| function getTotalIncome() { | ||
| // TODO: Implement this function | ||
| /* | ||
| 5) getTransactionsByCategory(category) - Filter transactions | ||
| - Loop + push | ||
| */ | ||
| export function getTransactionsByCategory(category) { | ||
| const result = []; | ||
| const target = category.toLowerCase(); | ||
| for (const transaction of transactions) { | ||
| if (transaction.category.toLowerCase() === target) { | ||
| result.push(transaction); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| function getTotalExpenses() { | ||
| // TODO: Implement this function | ||
| /* | ||
| 6) getLargestExpense() - Find highest expense amount | ||
| */ | ||
| export function getLargestExpense() { | ||
| let largest = null; | ||
| for (const transaction of transactions) { | ||
| if (transaction.type === "expense") { | ||
| if (largest === null || transaction.amount > largest.amount) { | ||
| largest = transaction; | ||
| } | ||
| } | ||
| } | ||
| return largest; | ||
| } | ||
|
|
||
| function getBalance() { | ||
| // TODO: Implement this function | ||
| /* | ||
| 7) printAllTransactions() - Display all transactions with formatting | ||
| */ | ||
| export function printAllTransactions() { | ||
| console.log(chalk.bold("💰 PERSONAL FINANCE TRACKER 💰")); | ||
| console.log(""); | ||
| console.log(chalk.bold("All Transactions:")); | ||
| let i = 1; | ||
| for (const transaction of transactions) { | ||
| const { type, category, amount, description } = transaction; | ||
| const typeLabel = type.toUpperCase(); | ||
| const categoryColored = chalk.yellow(category); | ||
| const amountText = formatEUR(amount); | ||
| const amountColored = | ||
| type === "income" ? chalk.green(amountText) : chalk.red(amountText); | ||
| console.log( | ||
| `${i}. [${typeLabel}] ${description} - ${amountColored} (${categoryColored})` | ||
| ); | ||
|
|
||
| i = i + 1; | ||
| } | ||
| const totalIncome = getTotalIncome(); | ||
| const totalExpenses = getTotalExpenses(); | ||
| const balance = getBalance(); | ||
| const count = transactions.length; | ||
| const largestExpense = getLargestExpense(); | ||
| console.log(""); | ||
| console.log(chalk.bold("📊 FINANCIAL SUMMARY 📊")); | ||
|
|
||
| console.log(chalk.bold(`Total Income: ${chalk.green(formatEUR(totalIncome))}`)); | ||
| console.log( | ||
| chalk.bold(`Total Expenses: ${chalk.red(formatEUR(totalExpenses))}`) | ||
| ); | ||
| const balanceColored = | ||
| balance >= 0 ? chalk.cyan(formatEUR(balance)) : chalk.red(formatEUR(balance)); | ||
| console.log(chalk.bold(`Current Balance: ${balanceColored}`)); | ||
| console.log(chalk.bold(`Total Transactions: ${count}`)); | ||
| if (largestExpense) { | ||
| console.log( | ||
| chalk.bold( | ||
| `Largest Expense: ${largestExpense.description} (${chalk.red( | ||
| formatEUR(largestExpense.amount) | ||
| )})` | ||
| ) | ||
| ); | ||
| } else { | ||
| console.log(chalk.bold("Largest Expense: none")); | ||
| } | ||
| } | ||
|
|
||
| /* Bonus Challenges*/ | ||
|
|
||
| /* | ||
| Bonus 1: Search transactions by date range using slice | ||
| - Copy + sort by date | ||
| - Find start and end indices | ||
| - Return slice(startIndex, endIndex+1) | ||
| */ | ||
| export function getTransactionsByDateRange(startDate, endDate) { | ||
| const sorted = [...transactions].sort((a, b) => a.date.localeCompare(b.date)); | ||
| let startIndex = -1; | ||
| let endIndex = -1; | ||
| // Find first index with date >= startDate | ||
| for (let i = 0; i < sorted.length; i++) { | ||
| if (sorted[i].date >= startDate) { | ||
| startIndex = i; | ||
| break; | ||
| } | ||
| } | ||
| // Find last index with date <= endDate | ||
| for (let i = sorted.length - 1; i >= 0; i--) { | ||
| if (sorted[i].date <= endDate) { | ||
| endIndex = i; | ||
| break; | ||
| } | ||
| } | ||
| if (startIndex === -1 || endIndex === -1 || startIndex > endIndex) { | ||
| return []; | ||
| } | ||
| return sorted.slice(startIndex, endIndex + 1); | ||
| } | ||
|
|
||
| function getTransactionsByCategory(category) { | ||
| // TODO: Implement this function | ||
| /* | ||
| Bonus 2: Group transactions by month using nested objects | ||
| */ | ||
| export function groupTransactionsByMonth() { | ||
| const groups = {}; | ||
| for (const transaction of transactions) { | ||
| const month = transaction.date.slice(0, 7); // "YYYY-MM" | ||
| if (!groups[month]) { | ||
| groups[month] = { income: [], expense: [] }; | ||
| } | ||
| if (transaction.type === "income") groups[month].income.push(transaction); | ||
| if (transaction.type === "expense") groups[month].expense.push(transaction); | ||
| } | ||
| return groups; | ||
| } | ||
|
|
||
| function getLargestExpense() { | ||
| // TODO: Implement this function | ||
| /* | ||
| Bonus 3: Calculate average expense per category | ||
| */ | ||
| export function getAverageExpensePerCategory() { | ||
| const categorySumCount = {}; | ||
| for (const transaction of transactions) { | ||
| if (transaction.type !== "expense") continue; | ||
| const c = transaction.category; | ||
| if (!categorySumCount[c]) categorySumCount[c] = { sum: 0, count: 0 }; | ||
| categorySumCount[c].sum = categorySumCount[c].sum + transaction.amount; | ||
| categorySumCount[c].count = categorySumCount[c].count + 1; | ||
| } | ||
| const averages = {}; | ||
| for (const category of Object.keys(categorySumCount)) { | ||
| averages[category] = categorySumCount[category].sum / categorySumCount[category].count; | ||
| } | ||
| return averages; | ||
| } | ||
|
|
||
| function printAllTransactions() { | ||
| // TODO: Implement this function | ||
| } | ||
| /* | ||
| Bonus 4: Remove transaction by id | ||
|
|
||
| */ | ||
| export function removeTransactionById(id) { | ||
| for (let i = 0; i < transactions.length; i++) { | ||
| if (transactions[i].id === id) { | ||
| const removed = transactions.splice(i, 1); // returns array of removed items | ||
| return removed[0]; | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| /* | ||
| Bonus 5: Create a function that finds consecutive expensive months | ||
| */ | ||
| export function findConsecutiveExpensiveMonths(threshold) { | ||
| const groups = groupTransactionsByMonth(); | ||
| const months = Object.keys(groups).sort(); // chronological order | ||
| // Build monthly expense totals | ||
| const monthlyExpense = {}; | ||
| for (const month of months) { | ||
| let sum = 0; | ||
| for (const transaction of groups[month].expense) { | ||
| sum = sum + transaction.amount; | ||
| } | ||
| monthlyExpense[month] = sum; | ||
| } | ||
| const sequences = []; | ||
| let i = 0; | ||
| // while loop | ||
| while (i < months.length) { | ||
| const month = months[i]; | ||
| if (monthlyExpense[month] >= threshold) { | ||
| const seq = [month]; | ||
| i = i + 1; | ||
| // Keep going while next months are also expensive | ||
| while (i < months.length && monthlyExpense[months[i]] >= threshold) { | ||
| seq.push(months[i]); | ||
| i = i + 1; | ||
| } | ||
| // Save only if sequence has at least 2 months | ||
| if (seq.length >= 2) { | ||
| sequences.push(seq); | ||
| } | ||
| } else { | ||
| i = i + 1; | ||
| } | ||
| } | ||
| return sequences; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Chronological order? Or alphabetical? 🤔 That'll definitely affect the output.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks! You’re right — .sort() here sorts the keys alphabetically.