Merge pull request #1552 from microsoft/softchris-patch-9
docs: modernization - the restpull/1566/head
commit
627f67f409
@ -1,11 +1,87 @@
|
||||
# Data Types Practice
|
||||
# Data Types Practice: E-commerce Shopping Cart
|
||||
|
||||
## Instructions
|
||||
|
||||
Imagine you are building a shopping cart. Write documentation on the data types you would need to complete your shopping experience. For each data type, explain how and why you would use it, and provide an example. The six JavaScript data types are: String, Number, Boolean, Null, Undefined, and Object.
|
||||
Imagine you are building a modern e-commerce shopping cart system. This assignment will help you understand how different JavaScript data types work together to create real-world applications.
|
||||
|
||||
### Your Task
|
||||
|
||||
Create a comprehensive analysis of how you would use JavaScript data types in a shopping cart application. For each of the seven primitive data types and objects, you need to:
|
||||
|
||||
1. **Identify** the data type and its purpose
|
||||
2. **Explain** why this data type is the best choice for specific shopping cart features
|
||||
3. **Provide** realistic code examples showing the data type in action
|
||||
4. **Describe** how this data type interacts with other parts of the shopping cart
|
||||
|
||||
### Required Data Types to Cover
|
||||
|
||||
**Primitive Data Types:**
|
||||
- **String**: Product names, descriptions, user information
|
||||
- **Number**: Prices, quantities, tax calculations
|
||||
- **Boolean**: Item availability, user preferences, cart status
|
||||
- **Null**: Intentionally empty values (like missing discount codes)
|
||||
- **Undefined**: Uninitialized values or missing data
|
||||
- **Symbol**: Unique identifiers (advanced use)
|
||||
- **BigInt**: Large financial calculations (advanced use)
|
||||
|
||||
**Reference Types:**
|
||||
- **Object**: Product details, user profiles, cart contents
|
||||
- **Array**: List of products, order history, categories
|
||||
|
||||
### Example Format for Each Data Type
|
||||
|
||||
For each data type, structure your response like this:
|
||||
|
||||
```markdown
|
||||
## [Data Type Name]
|
||||
|
||||
**Purpose in Shopping Cart:** [Explain what this data type does]
|
||||
|
||||
**Why This Type:** [Explain why this is the best choice]
|
||||
|
||||
**Code Example:**
|
||||
```javascript
|
||||
// Your realistic code example here
|
||||
```
|
||||
|
||||
**Real-world Usage:** [Describe how this would work in practice]
|
||||
|
||||
**Interactions:** [Explain how this data type works with others]
|
||||
```
|
||||
|
||||
### Bonus Challenges
|
||||
|
||||
1. **Type Coercion**: Show an example where JavaScript automatically converts between data types in your shopping cart (e.g., string "5" + number 10)
|
||||
|
||||
2. **Data Validation**: Demonstrate how you would check if user input is the correct data type before processing
|
||||
|
||||
3. **Performance Considerations**: Explain when you might choose one data type over another for performance reasons
|
||||
|
||||
### Submission Guidelines
|
||||
|
||||
- Create a markdown document with clear headings for each data type
|
||||
- Include working JavaScript code examples
|
||||
- Use realistic e-commerce scenarios in your examples
|
||||
- Explain your reasoning clearly for beginners to understand
|
||||
- Test your code examples to ensure they work correctly
|
||||
|
||||
## Rubric
|
||||
|
||||
Criteria | Exemplary | Adequate | Needs Improvement
|
||||
--- | --- | --- | -- |
|
||||
Data Types | All six data types are listed, explored in detail, and documented with examples | Four data types are explored with some explanation | Two data types are explored with minimal explanation |
|
||||
| Criteria | Exemplary (90-100%) | Proficient (80-89%) | Developing (70-79%) | Needs Improvement (Below 70%) |
|
||||
|----------|---------------------|---------------------|---------------------|------------------------------|
|
||||
| **Data Type Coverage** | All 7 primitive types and objects/arrays covered with detailed explanations | 6-7 data types covered with good explanations | 4-5 data types covered with basic explanations | Fewer than 4 data types or minimal explanations |
|
||||
| **Code Examples** | All examples are realistic, working, and well-commented | Most examples work and are relevant to e-commerce | Some examples work but may be generic | Code examples are incomplete or non-functional |
|
||||
| **Real-world Application** | Clearly connects each data type to practical shopping cart features | Good connection to e-commerce scenarios | Some connection to shopping cart context | Limited real-world application demonstrated |
|
||||
| **Technical Accuracy** | All technical information is correct and demonstrates deep understanding | Most technical information is accurate | Generally accurate with minor errors | Contains significant technical errors |
|
||||
| **Communication** | Explanations are clear, beginner-friendly, and well-organized | Good explanations that are mostly clear | Explanations are understandable but may lack clarity | Explanations are unclear or poorly organized |
|
||||
| **Bonus Elements** | Includes multiple bonus challenges with excellent execution | Includes one or more bonus challenges well done | Attempts bonus challenges with mixed success | No bonus challenges attempted |
|
||||
|
||||
### Learning Objectives
|
||||
|
||||
By completing this assignment, you will:
|
||||
- ✅ **Understand** the seven JavaScript primitive data types and their uses
|
||||
- ✅ **Apply** data types to real-world programming scenarios
|
||||
- ✅ **Analyze** when to choose specific data types for different purposes
|
||||
- ✅ **Create** working code examples that demonstrate data type usage
|
||||
- ✅ **Explain** technical concepts in beginner-friendly language
|
||||
- ✅ **Connect** fundamental programming concepts to practical applications
|
||||
@ -1,40 +1,104 @@
|
||||
# Operators
|
||||
# Making Decisions: Student Grade Processor
|
||||
|
||||
## Instructions
|
||||
## Learning Objectives
|
||||
|
||||
Play around with operators. Here's a suggestion for a program you can implement:
|
||||
In this assignment, you'll practice the decision-making concepts from this lesson by building a program that processes student grades from different grading systems. You'll use `if...else` statements, comparison operators, and logical operators to determine which students pass their courses.
|
||||
|
||||
You have a set of students from two different grading systems.
|
||||
## The Challenge
|
||||
|
||||
### First grading system
|
||||
You work for a school that recently merged with another institution. Now you need to process student grades from two completely different grading systems and determine which students are passing. This is a perfect opportunity to practice conditional logic!
|
||||
|
||||
One grading system is defined as grades being from 1-5 where 3 and above means you pass the course.
|
||||
### Understanding the Grading Systems
|
||||
|
||||
### Second grading system
|
||||
#### First Grading System (Numeric)
|
||||
- Grades are given as numbers from 1-5
|
||||
- **Passing grade**: 3 and above (3, 4, or 5)
|
||||
- **Failing grade**: Below 3 (1 or 2)
|
||||
|
||||
The other grade system has the following grades `A, A-, B, B-, C, C-` where `A` is the top grade and `C` is the lowest passing grade.
|
||||
#### Second Grading System (Letter Grades)
|
||||
- Grades use letters: `A`, `A-`, `B`, `B-`, `C`, `C-`
|
||||
- **Passing grades**: `A`, `A-`, `B`, `B-`, `C`, `C-` (all listed grades are passing)
|
||||
- **Note**: This system doesn't include failing grades like `D` or `F`
|
||||
|
||||
### The task
|
||||
### Your Task
|
||||
|
||||
Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass.
|
||||
|
||||
> TIP, use a for-loop and if...else and comparison operators:
|
||||
Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass according to their respective grading systems.
|
||||
|
||||
```javascript
|
||||
let allStudents = [
|
||||
'A',
|
||||
'B-',
|
||||
1,
|
||||
4,
|
||||
5,
|
||||
2
|
||||
]
|
||||
'A', // Letter grade - passing
|
||||
'B-', // Letter grade - passing
|
||||
1, // Numeric grade - failing
|
||||
4, // Numeric grade - passing
|
||||
5, // Numeric grade - passing
|
||||
2 // Numeric grade - failing
|
||||
];
|
||||
|
||||
let studentsWhoPass = [];
|
||||
```
|
||||
|
||||
### Step-by-Step Approach
|
||||
|
||||
1. **Set up a loop** to go through each grade in the `allStudents` array
|
||||
2. **Check the grade type** (is it a number or a string?)
|
||||
3. **Apply the appropriate grading system rules**:
|
||||
- For numbers: check if grade >= 3
|
||||
- For strings: check if it's one of the valid passing letter grades
|
||||
4. **Add passing grades** to the `studentsWhoPass` array
|
||||
|
||||
### Helpful Code Techniques
|
||||
|
||||
Use these JavaScript concepts from the lesson:
|
||||
|
||||
- **typeof operator**: `typeof grade === 'number'` to check if it's a numeric grade
|
||||
- **Comparison operators**: `>=` to compare numeric grades
|
||||
- **Logical operators**: `||` to check multiple letter grade conditions
|
||||
- **if...else statements**: to handle different grading systems
|
||||
- **Array methods**: `.push()` to add passing grades to your new array
|
||||
|
||||
### Expected Output
|
||||
|
||||
When you run your program, `studentsWhoPass` should contain: `['A', 'B-', 4, 5]`
|
||||
|
||||
**Why these grades pass:**
|
||||
- `'A'` and `'B-'` are valid letter grades (all letter grades in this system are passing)
|
||||
- `4` and `5` are numeric grades >= 3
|
||||
- `1` and `2` fail because they're numeric grades < 3
|
||||
|
||||
## Testing Your Solution
|
||||
|
||||
Test your code with different scenarios:
|
||||
|
||||
```javascript
|
||||
// Test with different grade combinations
|
||||
let testGrades1 = ['A-', 3, 'C', 1, 'B'];
|
||||
let testGrades2 = [5, 'A', 2, 'C-', 4];
|
||||
|
||||
// Your solution should work with any combination of valid grades
|
||||
```
|
||||
|
||||
## Bonus Challenges
|
||||
|
||||
Once you complete the basic assignment, try these extensions:
|
||||
|
||||
1. **Add validation**: Check for invalid grades (like negative numbers or invalid letters)
|
||||
2. **Count statistics**: Calculate how many students pass vs. fail
|
||||
3. **Grade conversion**: Convert all grades to a single numeric system (A=5, B=4, C=3, etc.)
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ------------------------------ | ----------------------------- | ------------------------------- |
|
||||
| | Complete solution is presented | Partial solution is presented | Solution with bugs is presented |
|
||||
| Criteria | Exemplary (4) | Proficient (3) | Developing (2) | Beginning (1) |
|
||||
|----------|---------------|----------------|----------------|---------------|
|
||||
| **Functionality** | Program correctly identifies all passing grades from both systems | Program works with minor issues or edge cases | Program partially works but has logical errors | Program has significant errors or doesn't run |
|
||||
| **Code Structure** | Clean, well-organized code with proper if...else logic | Good structure with appropriate conditional statements | Acceptable structure with some organizational issues | Poor structure, difficult to follow logic |
|
||||
| **Use of Concepts** | Effectively uses comparison operators, logical operators, and conditional statements | Good use of lesson concepts with minor gaps | Some use of lesson concepts but missing key elements | Limited use of lesson concepts |
|
||||
| **Problem Solving** | Shows clear understanding of the problem and elegant solution approach | Good problem-solving approach with solid logic | Adequate problem-solving with some confusion | Unclear approach, doesn't demonstrate understanding |
|
||||
|
||||
## Submission Guidelines
|
||||
|
||||
1. **Test your code** thoroughly with the provided examples
|
||||
2. **Add comments** explaining your logic, especially for the conditional statements
|
||||
3. **Verify output** matches expected results: `['A', 'B-', 4, 5]`
|
||||
4. **Consider edge cases** like empty arrays or unexpected data types
|
||||
|
||||
> 💡 **Pro Tip**: Start simple! Get the basic functionality working first, then add more sophisticated features. Remember, the goal is to practice decision-making logic with the tools you learned in this lesson.
|
||||
|
||||
@ -1,13 +1,108 @@
|
||||
# Loop an Array
|
||||
# Arrays and Loops Assignment
|
||||
|
||||
## Instructions
|
||||
|
||||
Complete the following exercises to practice working with arrays and loops. Each exercise builds on concepts from the lesson and encourages you to apply different loop types and array methods.
|
||||
|
||||
### Exercise 1: Number Pattern Generator
|
||||
Create a program that lists every 3rd number between 1-20 and prints it to the console.
|
||||
|
||||
> TIP: use a for-loop and modify the iteration-expression
|
||||
**Requirements:**
|
||||
- Use a `for` loop with a custom increment
|
||||
- Display numbers in a user-friendly format
|
||||
- Add descriptive comments explaining your logic
|
||||
|
||||
**Expected Output:**
|
||||
```
|
||||
3, 6, 9, 12, 15, 18
|
||||
```
|
||||
|
||||
> **Tip:** Modify the iteration-expression in your for loop to skip numbers.
|
||||
|
||||
### Exercise 2: Array Analysis
|
||||
Create an array of at least 8 different numbers and write functions to analyze the data.
|
||||
|
||||
**Requirements:**
|
||||
- Create an array called `numbers` with at least 8 values
|
||||
- Write a function `findMaximum()` that returns the highest number
|
||||
- Write a function `findMinimum()` that returns the lowest number
|
||||
- Write a function `calculateSum()` that returns the total of all numbers
|
||||
- Test each function and display the results
|
||||
|
||||
**Bonus Challenge:** Create a function that finds the second highest number in the array.
|
||||
|
||||
### Exercise 3: String Array Processing
|
||||
Create an array of your favorite movies/books/songs and practice different loop types.
|
||||
|
||||
**Requirements:**
|
||||
- Create an array with at least 5 string values
|
||||
- Use a traditional `for` loop to display items with numbers (1. Item Name)
|
||||
- Use a `for...of` loop to display items in uppercase
|
||||
- Use `forEach()` method to count and display the total characters
|
||||
|
||||
**Example Output:**
|
||||
```
|
||||
Traditional for loop:
|
||||
1. The Matrix
|
||||
2. Inception
|
||||
3. Interstellar
|
||||
|
||||
For...of loop (uppercase):
|
||||
THE MATRIX
|
||||
INCEPTION
|
||||
INTERSTELLAR
|
||||
|
||||
Character count:
|
||||
Total characters across all titles: 42
|
||||
```
|
||||
|
||||
### Exercise 4: Data Filtering (Advanced)
|
||||
Create a program that processes an array of objects representing students.
|
||||
|
||||
**Requirements:**
|
||||
- Create an array of at least 5 student objects with properties: `name`, `age`, `grade`
|
||||
- Use loops to find students who are 18 or older
|
||||
- Calculate the average grade of all students
|
||||
- Create a new array containing only students with grades above 85
|
||||
|
||||
**Example Structure:**
|
||||
```javascript
|
||||
const students = [
|
||||
{ name: "Alice", age: 17, grade: 92 },
|
||||
{ name: "Bob", age: 18, grade: 84 },
|
||||
// Add more students...
|
||||
];
|
||||
```
|
||||
|
||||
## Testing Your Code
|
||||
|
||||
Test your programs by:
|
||||
1. Running each exercise in your browser's console
|
||||
2. Verifying outputs match expected results
|
||||
3. Testing with different data sets
|
||||
4. Checking that your code handles edge cases (empty arrays, single elements)
|
||||
|
||||
## Submission Guidelines
|
||||
|
||||
Include the following in your submission:
|
||||
- Well-commented JavaScript code for each exercise
|
||||
- Screenshots or text output showing your programs running
|
||||
- Brief explanation of which loop type you chose for each task and why
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | --------------------------------------- | ------------------------ | ------------------------------ |
|
||||
| | Program runs correctly and is commented | Program is not commented | Program is incomplete or buggy |
|
||||
| Criteria | Exemplary (3 points) | Adequate (2 points) | Needs Improvement (1 point) |
|
||||
| -------- | -------------------- | ------------------- | --------------------------- |
|
||||
| **Functionality** | All exercises completed correctly with bonus challenges | All required exercises work correctly | Some exercises incomplete or contain errors |
|
||||
| **Code Quality** | Clean, well-organized code with descriptive variable names | Code works but could be cleaner | Code is messy or hard to understand |
|
||||
| **Comments** | Comprehensive comments explaining logic and decisions | Basic comments present | Minimal or no comments |
|
||||
| **Loop Usage** | Demonstrates understanding of different loop types appropriately | Uses loops correctly but limited variety | Incorrect or inefficient loop usage |
|
||||
| **Testing** | Evidence of thorough testing with multiple scenarios | Basic testing demonstrated | Little evidence of testing |
|
||||
|
||||
## Reflection Questions
|
||||
|
||||
After completing the exercises, consider:
|
||||
1. Which type of loop felt most natural to use and why?
|
||||
2. What challenges did you encounter when working with arrays?
|
||||
3. How could these skills apply to real-world web development projects?
|
||||
4. What would you do differently if you had to optimize your code for performance?
|
||||
@ -1,11 +1,123 @@
|
||||
# Work a bit more with the DOM
|
||||
# DOM Element Investigation Assignment
|
||||
|
||||
## Overview
|
||||
|
||||
Now that you've experienced the power of DOM manipulation firsthand, it's time to explore the broader world of DOM interfaces. This assignment will deepen your understanding of how different web technologies interact with the DOM beyond just dragging elements.
|
||||
|
||||
## Learning Objectives
|
||||
|
||||
By completing this assignment, you will:
|
||||
- **Research** and understand a specific DOM interface in depth
|
||||
- **Analyze** real-world implementations of DOM manipulation
|
||||
- **Connect** theoretical concepts to practical applications
|
||||
- **Develop** skills in technical documentation and analysis
|
||||
|
||||
## Instructions
|
||||
|
||||
Research the DOM a little more by 'adopting' a DOM element. Visit the MDN's [list of DOM interfaces](https://developer.mozilla.org/docs/Web/API/Document_Object_Model) and pick one. Find it being used on a web site in the web, and write an explanation of how it is used.
|
||||
### Step 1: Choose Your DOM Interface
|
||||
|
||||
Visit MDN's comprehensive [list of DOM interfaces](https://developer.mozilla.org/docs/Web/API/Document_Object_Model) and select one interface that interests you. Consider choosing from these categories for variety:
|
||||
|
||||
**Beginner-Friendly Options:**
|
||||
- `Element.classList` - Managing CSS classes dynamically
|
||||
- `Document.querySelector()` - Advanced element selection
|
||||
- `Element.addEventListener()` - Event handling beyond pointer events
|
||||
- `Window.localStorage` - Client-side data storage
|
||||
|
||||
**Intermediate Challenges:**
|
||||
- `Intersection Observer API` - Detecting element visibility
|
||||
- `MutationObserver` - Watching DOM changes
|
||||
- `Drag and Drop API` - Alternative to our pointer-based approach
|
||||
- `Geolocation API` - Accessing user location
|
||||
|
||||
**Advanced Exploration:**
|
||||
- `Web Components` - Custom elements and shadow DOM
|
||||
- `Canvas API` - Programmatic graphics
|
||||
- `Web Workers` - Background processing
|
||||
- `Service Workers` - Offline functionality
|
||||
|
||||
### Step 2: Research and Document
|
||||
|
||||
Create a comprehensive analysis (300-500 words) that includes:
|
||||
|
||||
#### Technical Overview
|
||||
- **Define** what your chosen interface does in clear, beginner-friendly language
|
||||
- **Explain** the key methods, properties, or events it provides
|
||||
- **Describe** the types of problems it's designed to solve
|
||||
|
||||
#### Real-World Implementation
|
||||
- **Find** a website that uses your chosen interface (inspect the code or research examples)
|
||||
- **Document** the specific implementation with code snippets if possible
|
||||
- **Analyze** why the developers chose this approach
|
||||
- **Explain** how it enhances the user experience
|
||||
|
||||
#### Practical Application
|
||||
- **Compare** your interface to the techniques we used in the terrarium project
|
||||
- **Suggest** how your interface could enhance or extend the terrarium functionality
|
||||
- **Identify** other projects where this interface would be valuable
|
||||
|
||||
### Step 3: Code Example
|
||||
|
||||
Include a simple, working code example that demonstrates your interface in action. This should be:
|
||||
- **Functional** - The code should actually work when tested
|
||||
- **Commented** - Explain what each part does
|
||||
- **Relevant** - Connected to a realistic use case
|
||||
- **Beginner-friendly** - Understandable to someone learning web development
|
||||
|
||||
## Submission Format
|
||||
|
||||
Structure your submission with clear headings:
|
||||
|
||||
```markdown
|
||||
# [Interface Name] DOM Investigation
|
||||
|
||||
## What It Does
|
||||
[Technical overview]
|
||||
|
||||
## Real-World Example
|
||||
[Website analysis and implementation details]
|
||||
|
||||
## Code Demonstration
|
||||
[Your working example with comments]
|
||||
|
||||
## Reflection
|
||||
[How this connects to our terrarium project and future applications]
|
||||
```
|
||||
|
||||
## Assessment Rubric
|
||||
|
||||
| Criteria | Exemplary (A) | Proficient (B) | Developing (C) | Needs Improvement (D) |
|
||||
|----------|---------------|----------------|----------------|----------------------|
|
||||
| **Technical Understanding** | Demonstrates deep understanding with accurate explanations and proper terminology | Shows solid understanding with mostly accurate explanations | Basic understanding with some misconceptions | Limited understanding with significant errors |
|
||||
| **Real-World Analysis** | Identifies and thoroughly analyzes actual implementation with specific examples | Finds real example with adequate analysis | Locates example but analysis lacks depth | Vague or inaccurate real-world connection |
|
||||
| **Code Example** | Working, well-commented code that clearly demonstrates the interface | Functional code with adequate comments | Code works but needs better documentation | Code has errors or poor explanation |
|
||||
| **Writing Quality** | Clear, engaging writing with proper structure and technical communication | Well-organized with good technical writing | Adequate organization and clarity | Poor organization or unclear communication |
|
||||
| **Critical Thinking** | Makes insightful connections between concepts and suggests innovative applications | Shows good analytical thinking and relevant connections | Some analysis present but could be deeper | Limited evidence of critical thinking |
|
||||
|
||||
## Tips for Success
|
||||
|
||||
**Research Strategies:**
|
||||
- **Start** with MDN documentation for authoritative information
|
||||
- **Look** for code examples on GitHub or CodePen
|
||||
- **Check** popular websites using browser developer tools
|
||||
- **Watch** tutorial videos for visual explanations
|
||||
|
||||
**Writing Guidelines:**
|
||||
- **Use** your own words rather than copying documentation
|
||||
- **Include** specific examples and code snippets
|
||||
- **Explain** technical concepts as if teaching a friend
|
||||
- **Connect** your interface to broader web development concepts
|
||||
|
||||
**Code Example Ideas:**
|
||||
- **Create** a simple demo that showcases the interface's main features
|
||||
- **Build** on concepts from our terrarium project where relevant
|
||||
- **Focus** on functionality over visual design
|
||||
- **Test** your code to ensure it works correctly
|
||||
|
||||
## Submission Deadline
|
||||
|
||||
[Insert deadline here]
|
||||
|
||||
## Rubric
|
||||
## Questions?
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | --------------------------------------------- | ------------------------------------------------ | ----------------------- |
|
||||
| | Paragraph write-up is presented, with example | Paragraph write-up is presented, without example | No writeup is presented |
|
||||
If you need clarification on any aspect of this assignment, don't hesitate to ask! This investigation will deepen your understanding of how the DOM enables the interactive web experiences we use every day.
|
||||
|
||||
@ -1,11 +1,130 @@
|
||||
# Restyle your Extension
|
||||
# Assignment: Restyle Your Browser Extension
|
||||
|
||||
## Overview
|
||||
|
||||
Now that you've built the HTML structure for your carbon footprint browser extension, it's time to make it visually appealing and user-friendly. Great design enhances the user experience and makes your extension more professional and engaging.
|
||||
|
||||
Your extension comes with basic CSS styling, but this assignment challenges you to create a unique visual identity that reflects your personal style while maintaining excellent usability.
|
||||
|
||||
## Instructions
|
||||
|
||||
The codebase for this extension comes complete with styles, but you don't have to use them; make your extension your own by restyling it by editing its css file.
|
||||
### Part 1: Analyze the Current Design
|
||||
|
||||
Before making changes, examine the existing CSS structure:
|
||||
|
||||
1. **Locate** the CSS files in your extension project
|
||||
2. **Review** the current styling approach and color scheme
|
||||
3. **Identify** areas for improvement in layout, typography, and visual hierarchy
|
||||
4. **Consider** how the design supports user goals (easy form completion and clear data display)
|
||||
|
||||
### Part 2: Design Your Custom Styling
|
||||
|
||||
Create a cohesive visual design that includes:
|
||||
|
||||
**Color Scheme:**
|
||||
- Choose a primary color palette that reflects environmental themes
|
||||
- Ensure sufficient contrast for accessibility (use tools like WebAIM's contrast checker)
|
||||
- Consider how colors will look across different browser themes
|
||||
|
||||
**Typography:**
|
||||
- Select readable fonts that work well at small extension sizes
|
||||
- Establish a clear hierarchy with appropriate font sizes and weights
|
||||
- Ensure text remains legible in both light and dark browser themes
|
||||
|
||||
**Layout and Spacing:**
|
||||
- Improve the visual organization of form elements and data display
|
||||
- Add appropriate padding and margins for better readability
|
||||
- Consider responsive design principles for different screen sizes
|
||||
|
||||
### Part 3: Implement Your Design
|
||||
|
||||
Modify the CSS files to implement your design:
|
||||
|
||||
```css
|
||||
/* Example starting points for customization */
|
||||
|
||||
.form-data {
|
||||
/* Style the configuration form */
|
||||
background: /* your choice */;
|
||||
padding: /* your spacing */;
|
||||
border-radius: /* your preference */;
|
||||
}
|
||||
|
||||
.result-container {
|
||||
/* Style the data display area */
|
||||
background: /* complementary color */;
|
||||
border: /* your border style */;
|
||||
margin: /* your spacing */;
|
||||
}
|
||||
|
||||
/* Add your custom styles here */
|
||||
```
|
||||
|
||||
**Key areas to style:**
|
||||
- **Form elements**: Input fields, labels, and submit button
|
||||
- **Results display**: Data container, text styling, and loading states
|
||||
- **Interactive elements**: Hover effects, button states, and transitions
|
||||
- **Overall layout**: Container spacing, background colors, and visual hierarchy
|
||||
|
||||
### Part 4: Test and Refine
|
||||
|
||||
1. **Build** your extension with `npm run build`
|
||||
2. **Load** the updated extension into your browser
|
||||
3. **Test** all visual states (form entry, loading, results display, errors)
|
||||
4. **Verify** accessibility with browser developer tools
|
||||
5. **Refine** your styles based on actual usage
|
||||
|
||||
## Creative Challenges
|
||||
|
||||
### Basic Level
|
||||
- Update colors and fonts to create a cohesive theme
|
||||
- Improve spacing and alignment throughout the interface
|
||||
- Add subtle hover effects to interactive elements
|
||||
|
||||
### Intermediate Level
|
||||
- Design custom icons or graphics for your extension
|
||||
- Implement smooth transitions between different states
|
||||
- Create a unique loading animation for API calls
|
||||
|
||||
### Advanced Level
|
||||
- Design multiple theme options (light/dark/high-contrast)
|
||||
- Implement responsive design for different browser window sizes
|
||||
- Add micro-interactions that enhance the user experience
|
||||
|
||||
## Submission Guidelines
|
||||
|
||||
Your completed assignment should include:
|
||||
|
||||
- **Modified CSS files** with your custom styling
|
||||
- **Screenshots** showing your extension in different states (form, loading, results)
|
||||
- **Brief description** (2-3 sentences) explaining your design choices and how they improve the user experience
|
||||
|
||||
## Assessment Rubric
|
||||
|
||||
| Criteria | Exemplary (4) | Proficient (3) | Developing (2) | Beginning (1) |
|
||||
|----------|---------------|----------------|----------------|----------------|
|
||||
| **Visual Design** | Creative, cohesive design that enhances usability and reflects strong design principles | Good design choices with consistent styling and clear visual hierarchy | Basic design improvements with some consistency issues | Minimal styling changes or inconsistent design |
|
||||
| **Functionality** | All styles work perfectly across different states and browser environments | Styles work well with minor issues in edge cases | Most styles functional with some display problems | Significant styling issues that impact usability |
|
||||
| **Code Quality** | Clean, well-organized CSS with meaningful class names and efficient selectors | Good CSS structure with appropriate use of selectors and properties | Acceptable CSS with some organization issues | Poor CSS structure or overly complex styling |
|
||||
| **Accessibility** | Excellent color contrast, readable fonts, and consideration for users with disabilities | Good accessibility practices with minor areas for improvement | Basic accessibility considerations with some issues | Limited attention to accessibility requirements |
|
||||
|
||||
## Tips for Success
|
||||
|
||||
> 💡 **Design Tip**: Start with subtle changes and build up to more dramatic styling. Small improvements in typography and spacing often have big impacts on perceived quality.
|
||||
|
||||
**Best practices to follow:**
|
||||
- **Test** your extension in both light and dark browser themes
|
||||
- **Use** relative units (em, rem) for better scalability
|
||||
- **Maintain** consistent spacing using CSS custom properties
|
||||
- **Consider** how your design will look to users with different visual needs
|
||||
- **Validate** your CSS to ensure it follows proper syntax
|
||||
|
||||
> ⚠️ **Common Mistake**: Don't sacrifice usability for visual appeal. Your extension should be both beautiful and functional.
|
||||
|
||||
## Rubric
|
||||
**Remember to:**
|
||||
- **Keep** important information easily readable
|
||||
- **Ensure** buttons and interactive elements are easy to click
|
||||
- **Maintain** clear visual feedback for user actions
|
||||
- **Test** your design with real data, not just placeholder text
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | -------------------------------------------- | --------------------- | ----------------- |
|
||||
| | Code is submitted with functional new styles | Styling is incomplete | Styles are buggy |
|
||||
Good luck creating a browser extension that's both functional and visually stunning!
|
||||
@ -1,11 +1,93 @@
|
||||
# Adopt an API
|
||||
|
||||
## Overview
|
||||
|
||||
APIs open up endless possibilities for creative web development! In this assignment, you'll choose an external API and build a browser extension that solves a real problem or provides valuable functionality to users.
|
||||
|
||||
## Instructions
|
||||
|
||||
APIs can be very fun to play with. Here is a [list of many free ones](https://github.com/public-apis/public-apis). Pick an API, and build a browser extension that solves a problem. It can be as small a problem of not having enough pet pictures (so, try the [dog CEO API](https://dog.ceo/dog-api/)) or something bigger - have fun!
|
||||
### Step 1: Choose Your API
|
||||
Select an API from this curated [list of free public APIs](https://github.com/public-apis/public-apis). Consider these categories:
|
||||
|
||||
**Popular options for beginners:**
|
||||
- **Entertainment**: [Dog CEO API](https://dog.ceo/dog-api/) for random dog pictures
|
||||
- **Weather**: [OpenWeatherMap](https://openweathermap.org/api) for current weather data
|
||||
- **Quotes**: [Quotable API](https://quotable.io/) for inspirational quotes
|
||||
- **News**: [NewsAPI](https://newsapi.org/) for current headlines
|
||||
- **Fun Facts**: [Numbers API](http://numbersapi.com/) for interesting number facts
|
||||
|
||||
### Step 2: Plan Your Extension
|
||||
Before coding, answer these planning questions:
|
||||
- What problem does your extension solve?
|
||||
- Who is your target user?
|
||||
- What data will you store in local storage?
|
||||
- How will you handle API failures or rate limits?
|
||||
|
||||
### Step 3: Build Your Extension
|
||||
Your extension should include:
|
||||
|
||||
**Required Features:**
|
||||
- Form inputs for any required API parameters
|
||||
- API integration with proper error handling
|
||||
- Local storage for user preferences or API keys
|
||||
- Clean, responsive user interface
|
||||
- Loading states and user feedback
|
||||
|
||||
**Code Requirements:**
|
||||
- Use modern JavaScript (ES6+) features
|
||||
- Implement async/await for API calls
|
||||
- Include proper error handling with try/catch blocks
|
||||
- Add meaningful comments explaining your code
|
||||
- Follow consistent code formatting
|
||||
|
||||
### Step 4: Test and Polish
|
||||
- Test your extension with various inputs
|
||||
- Handle edge cases (no internet, invalid API responses)
|
||||
- Ensure your extension works after browser restart
|
||||
- Add user-friendly error messages
|
||||
|
||||
## Bonus Challenges
|
||||
|
||||
Take your extension to the next level:
|
||||
- Add multiple API endpoints for richer functionality
|
||||
- Implement data caching to reduce API calls
|
||||
- Create keyboard shortcuts for common actions
|
||||
- Add data export/import features
|
||||
- Implement user customization options
|
||||
|
||||
## Submission Requirements
|
||||
|
||||
1. **Working browser extension** that successfully integrates with your chosen API
|
||||
2. **README file** explaining:
|
||||
- Which API you chose and why
|
||||
- How to install and use your extension
|
||||
- Any API keys or setup required
|
||||
- Screenshots of your extension in action
|
||||
3. **Clean, commented code** following modern JavaScript practices
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | -------------------------------------------------------------------------- | ---------------------------------------- | ----------------------- |
|
||||
| | A complete browser extension is submitted using an API from the above list | A partial browser extension is submitted | The submission has bugs |
|
||||
| Criteria | Exemplary (90-100%) | Proficient (80-89%) | Developing (70-79%) | Beginning (60-69%) |
|
||||
|----------|---------------------|---------------------|---------------------|--------------------|
|
||||
| **API Integration** | Flawless API integration with comprehensive error handling and edge case management | Successful API integration with basic error handling | API works but has limited error handling | API integration has significant issues |
|
||||
| **Code Quality** | Clean, well-commented modern JavaScript following best practices | Good code structure with adequate comments | Code works but needs better organization | Poor code quality with minimal comments |
|
||||
| **User Experience** | Polished interface with excellent loading states and user feedback | Good interface with basic user feedback | Basic interface that functions adequately | Poor user experience with confusing interface |
|
||||
| **Local Storage** | Sophisticated use of local storage with data validation and management | Proper implementation of local storage for key features | Basic local storage implementation | Minimal or incorrect use of local storage |
|
||||
| **Documentation** | Comprehensive README with setup instructions and screenshots | Good documentation covering most requirements | Basic documentation missing some details | Poor or missing documentation |
|
||||
|
||||
## Getting Started Tips
|
||||
|
||||
1. **Start simple**: Choose an API that doesn't require complex authentication
|
||||
2. **Read the docs**: Thoroughly understand your chosen API's endpoints and responses
|
||||
3. **Plan your UI**: Sketch your extension's interface before coding
|
||||
4. **Test frequently**: Build incrementally and test each feature as you add it
|
||||
5. **Handle errors**: Always assume API calls might fail and plan accordingly
|
||||
|
||||
## Resources
|
||||
|
||||
- [Browser Extension Documentation](https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions)
|
||||
- [Fetch API Guide](https://developer.mozilla.org/docs/Web/API/Fetch_API/Using_Fetch)
|
||||
- [Local Storage Tutorial](https://developer.mozilla.org/docs/Web/API/Window/localStorage)
|
||||
- [JSON Parsing and Handling](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON)
|
||||
|
||||
Have fun building something useful and creative! 🚀
|
||||
@ -1,9 +1,93 @@
|
||||
# Analyze a site for performance
|
||||
|
||||
Provide a detailed report of a web site, showing areas where performance is problematic. Analyze why the site is slow and what you could do to speed it up. Don't rely only on the browser tools, but do some research on other tools that can help your report.
|
||||
## Assignment Overview
|
||||
|
||||
Performance analysis is a critical skill for modern web developers. In this assignment, you'll conduct a comprehensive performance audit of a real website, using both browser-based tools and third-party services to identify bottlenecks and propose optimization strategies.
|
||||
|
||||
Your task is to provide a detailed performance report that demonstrates your understanding of web performance principles and your ability to use professional analysis tools effectively.
|
||||
|
||||
## Assignment Instructions
|
||||
|
||||
**Choose a website** for analysis - select one of the following options:
|
||||
- A popular website you use frequently (news site, social media, e-commerce)
|
||||
- An open-source project website (GitHub pages, documentation sites)
|
||||
- A local business website or portfolio site
|
||||
- Your own project or previous coursework
|
||||
|
||||
**Conduct multi-tool analysis** using at least three different approaches:
|
||||
- **Browser DevTools** - Use Chrome/Edge Performance tab for detailed profiling
|
||||
- **Online auditing tools** - Try Lighthouse, GTmetrix, or WebPageTest
|
||||
- **Network analysis** - Examine resource loading, file sizes, and request patterns
|
||||
|
||||
**Document your findings** in a comprehensive report that includes:
|
||||
|
||||
### Performance Metrics Analysis
|
||||
- **Load time measurements** from multiple tools and perspectives
|
||||
- **Core Web Vitals** scores (LCP, FID, CLS) and their implications
|
||||
- **Resource breakdown** showing which assets contribute most to load time
|
||||
- **Network waterfall analysis** identifying blocking resources
|
||||
|
||||
### Problem Identification
|
||||
- **Specific performance bottlenecks** with supporting data
|
||||
- **Root cause analysis** explaining why each issue occurs
|
||||
- **User impact assessment** describing how problems affect real users
|
||||
- **Priority ranking** of issues based on severity and fixing difficulty
|
||||
|
||||
### Optimization Recommendations
|
||||
- **Specific, actionable improvements** with expected impact
|
||||
- **Implementation strategies** for each recommended change
|
||||
- **Modern best practices** that could be applied (lazy loading, compression, etc.)
|
||||
- **Tools and techniques** for ongoing performance monitoring
|
||||
|
||||
## Research Requirements
|
||||
|
||||
**Don't rely only on browser tools** - expand your analysis using:
|
||||
|
||||
**Third-party auditing services:**
|
||||
- [Google Lighthouse](https://developers.google.com/web/tools/lighthouse) - Comprehensive audits
|
||||
- [GTmetrix](https://gtmetrix.com/) - Performance and optimization insights
|
||||
- [WebPageTest](https://www.webpagetest.org/) - Real-world testing conditions
|
||||
- [Pingdom](https://tools.pingdom.com/) - Global performance monitoring
|
||||
|
||||
**Specialized analysis tools:**
|
||||
- [Bundle Analyzer](https://bundlephobia.com/) - JavaScript bundle size analysis
|
||||
- [Image optimization tools](https://squoosh.app/) - Asset optimization opportunities
|
||||
- [Security headers analysis](https://securityheaders.com/) - Security performance impact
|
||||
|
||||
## Deliverables Format
|
||||
|
||||
Create a professional report (2-3 pages) that includes:
|
||||
|
||||
1. **Executive Summary** - Key findings and recommendations overview
|
||||
2. **Methodology** - Tools used and testing approach
|
||||
3. **Current Performance Assessment** - Baseline metrics and measurements
|
||||
4. **Issues Identified** - Detailed problem analysis with supporting data
|
||||
5. **Recommendations** - Prioritized improvement strategies
|
||||
6. **Implementation Roadmap** - Step-by-step optimization plan
|
||||
|
||||
**Include visual evidence:**
|
||||
- Screenshots of performance tools and metrics
|
||||
- Charts or graphs showing performance data
|
||||
- Before/after comparisons where possible
|
||||
- Network waterfall charts and resource breakdowns
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------- |
|
||||
| | A report is presented with details drawn not only from browser tools but from 3rd party tools if available | A basic report is presented | A minimal report is presented |
|
||||
| Criteria | Exemplary (90-100%) | Adequate (70-89%) | Needs Improvement (50-69%) |
|
||||
| -------- | ------------------- | ----------------- | -------------------------- |
|
||||
| **Analysis Depth** | Comprehensive analysis using 4+ tools with detailed metrics, root cause analysis, and user impact assessment | Good analysis using 3 tools with clear metrics and basic problem identification | Basic analysis using 2 tools with limited depth and minimal problem identification |
|
||||
| **Tool Diversity** | Uses browser tools + 3+ third-party services with comparative analysis and insights from each | Uses browser tools + 2 third-party services with some comparative analysis | Uses browser tools + 1 third-party service with limited comparison |
|
||||
| **Problem Identification** | Identifies 5+ specific performance issues with detailed root cause analysis and quantified impact | Identifies 3-4 performance issues with good analysis and some impact measurement | Identifies 1-2 performance issues with basic analysis |
|
||||
| **Recommendations** | Provides specific, actionable recommendations with implementation details, expected impact, and modern best practices | Provides good recommendations with some implementation guidance and expected outcomes | Provides basic recommendations with limited implementation details |
|
||||
| **Professional Presentation** | Well-organized report with clear structure, visual evidence, executive summary, and professional formatting | Good organization with some visual evidence and clear structure | Basic organization with minimal visual evidence |
|
||||
|
||||
## Learning Outcomes
|
||||
|
||||
By completing this assignment, you will demonstrate your ability to:
|
||||
- **Apply** professional performance analysis tools and methodologies
|
||||
- **Identify** performance bottlenecks using data-driven analysis
|
||||
- **Analyze** the relationship between code quality and user experience
|
||||
- **Recommend** specific, actionable optimization strategies
|
||||
- **Communicate** technical findings in a professional format
|
||||
|
||||
This assignment reinforces the performance concepts learned in the lesson while building practical skills you'll use throughout your web development career.
|
||||
|
||||
@ -1,11 +1,86 @@
|
||||
# Mock up a game
|
||||
# Mock up a Game: Apply Design Patterns
|
||||
|
||||
## Assignment Overview
|
||||
|
||||
Put your newfound knowledge of design patterns to work by creating a simple game prototype! This assignment will help you practice both architectural patterns (inheritance or composition) and the pub/sub communication system you learned about in the lesson.
|
||||
|
||||
## Instructions
|
||||
|
||||
Using the code samples in the lesson, write a representation of a game you enjoy. It will have to be a simple game, but the goal is to use either the class or the composition pattern and the pub/sub pattern to show how a game might launch. Get creative!
|
||||
Create a simple game representation that demonstrates the design patterns from this lesson. Your game should be functional but doesn't need complex graphics \u2013 focus on the underlying architecture and communication patterns.
|
||||
|
||||
### Requirements
|
||||
|
||||
**Choose Your Architecture Pattern:**
|
||||
- **Option A**: Use class-based inheritance (like the `GameObject` → `Movable` → `Hero` example)
|
||||
- **Option B**: Use composition (like the factory function approach with mixed behaviors)
|
||||
|
||||
**Implement Communication:**
|
||||
- **Include** an `EventEmitter` class for pub/sub messaging
|
||||
- **Set up** at least 2-3 different message types (like `PLAYER_MOVE`, `ENEMY_SPAWN`, `SCORE_UPDATE`)
|
||||
- **Connect** user input (keyboard/mouse) to game events through the event system
|
||||
|
||||
**Game Elements to Include:**
|
||||
- At least one player-controlled character
|
||||
- At least one other game object (enemy, collectible, or environmental element)
|
||||
- Basic interaction between objects (collision, collection, or communication)
|
||||
|
||||
### Suggested Game Ideas
|
||||
|
||||
**Simple Games to Consider:**
|
||||
- **Snake Game** \u2013 Snake segments follow the head, food spawns randomly
|
||||
- **Pong Variation** \u2013 Paddle responds to input, ball bounces off walls
|
||||
- **Collector Game** \u2013 Player moves around collecting items while avoiding obstacles
|
||||
- **Tower Defense Basics** \u2013 Towers detect and shoot at moving enemies
|
||||
|
||||
### Code Structure Guidelines
|
||||
|
||||
```javascript
|
||||
// Example starting structure
|
||||
const Messages = {
|
||||
// Define your game messages here
|
||||
};
|
||||
|
||||
class EventEmitter {
|
||||
// Your event system implementation
|
||||
}
|
||||
|
||||
// Choose either class-based OR composition approach
|
||||
// Class-based example:
|
||||
class GameObject { /* base properties */ }
|
||||
class Player extends GameObject { /* player-specific behavior */ }
|
||||
|
||||
// OR Composition example:
|
||||
const gameObject = { /* base properties */ };
|
||||
const movable = { /* movement behavior */ };
|
||||
function createPlayer() { /* combine behaviors */ }
|
||||
```
|
||||
|
||||
### Testing Your Implementation
|
||||
|
||||
**Verify your code works by:**
|
||||
- **Testing** that objects move or change when events are triggered
|
||||
- **Confirming** that multiple objects can respond to the same event
|
||||
- **Checking** that you can add new behaviors without modifying existing code
|
||||
- **Ensuring** keyboard/mouse input properly triggers game events
|
||||
|
||||
## Submission Guidelines
|
||||
|
||||
**Your submission should include:**
|
||||
1. **JavaScript file(s)** with your game implementation
|
||||
2. **HTML file** to run and test your game (can be simple)
|
||||
3. **Comments** explaining which pattern you chose and why
|
||||
4. **Brief documentation** of your message types and what they do
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ------------------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------- |
|
||||
| | Three elements are placed on the screen and manipulated | Two elements are placed on the screen and manipulated | One element is placed on the screen and manipulated |
|
||||
| Criteria | Exemplary (3 points) | Adequate (2 points) | Needs Improvement (1 point) |
|
||||
|----------|---------------------|---------------------|------------------------------|
|
||||
| **Architecture Pattern** | Correctly implements either inheritance OR composition with clear class/object hierarchy | Uses chosen pattern with minor issues or inconsistencies | Attempts to use pattern but implementation has significant problems |
|
||||
| **Pub/Sub Implementation** | EventEmitter works correctly with multiple message types and proper event flow | Basic pub/sub system works with some event handling | Event system present but doesn't work reliably |
|
||||
| **Game Functionality** | Three or more interactive elements that communicate through events | Two interactive elements with basic event communication | One element responds to events or basic interaction |
|
||||
| **Code Quality** | Clean, well-commented code with logical organization and modern JavaScript | Generally well-organized code with adequate comments | Code works but lacks organization or clear commenting |
|
||||
|
||||
**Bonus Points:**
|
||||
- **Creative game mechanics** that showcase interesting uses of the patterns
|
||||
- **Multiple input methods** (keyboard AND mouse events)
|
||||
- **Scalable architecture** that would be easy to extend with new features
|
||||
@ -1,11 +1,67 @@
|
||||
# Play with the Canvas API
|
||||
# Assignment: Explore the Canvas API
|
||||
|
||||
## Learning Objectives
|
||||
|
||||
By completing this assignment, you will demonstrate your understanding of Canvas API fundamentals and apply creative problem-solving to build visual elements using JavaScript and HTML5 canvas.
|
||||
|
||||
## Instructions
|
||||
|
||||
Pick one element of the Canvas API and create something interesting around it. Can you create a little galaxy of repeated stars? Can you create an interesting texture of colored lines? You can look at CodePen for inspiration (but don't copy)
|
||||
Choose one aspect of the Canvas API that interests you and create an engaging visual project around it. This assignment encourages you to experiment with the drawing capabilities you've learned while building something uniquely yours.
|
||||
|
||||
### Project Ideas to Inspire You
|
||||
|
||||
**Geometric Patterns:**
|
||||
- **Create** a galaxy of animated twinkling stars using random positioning
|
||||
- **Design** an interesting texture using repeated geometric shapes
|
||||
- **Build** a kaleidoscope effect with rotating, colorful patterns
|
||||
|
||||
**Interactive Elements:**
|
||||
- **Develop** a drawing tool that responds to mouse movements
|
||||
- **Implement** shapes that change color when clicked
|
||||
- **Design** a simple animation loop with moving elements
|
||||
|
||||
**Game-Related Graphics:**
|
||||
- **Craft** a scrolling background for a space game
|
||||
- **Build** particle effects like explosions or magic spells
|
||||
- **Create** animated sprites with multiple frames
|
||||
|
||||
### Development Guidelines
|
||||
|
||||
**Research and Inspiration:**
|
||||
- **Browse** CodePen for creative canvas examples (for inspiration, not copying)
|
||||
- **Study** the [Canvas API documentation](https://developer.mozilla.org/docs/Web/API/Canvas_API) for additional methods
|
||||
- **Experiment** with different drawing functions, colors, and animations
|
||||
|
||||
**Technical Requirements:**
|
||||
- **Use** proper canvas setup with `getContext('2d')`
|
||||
- **Include** meaningful comments explaining your approach
|
||||
- **Test** your code thoroughly to ensure it runs without errors
|
||||
- **Apply** modern JavaScript syntax (const/let, arrow functions)
|
||||
|
||||
**Creative Expression:**
|
||||
- **Focus** on one Canvas API feature but explore it deeply
|
||||
- **Add** your own creative twist to make the project personal
|
||||
- **Consider** how your creation could be part of a larger application
|
||||
|
||||
### Submission Guidelines
|
||||
|
||||
Submit your completed project as a single HTML file with embedded CSS and JavaScript, or as separate files in a folder. Include a brief comment explaining your creative choices and the Canvas API features you explored.
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | --------------------------------------------------------- | ----------------------------------- | --------------------- |
|
||||
| | Code is submitted showing an interesting texture or shape | Code is submitted, but does not run | Code is not submitted |
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
|----------|-----------|----------|-------------------|
|
||||
| **Technical Implementation** | Canvas API used creatively with multiple features, code runs flawlessly, modern JavaScript syntax applied | Canvas API used correctly, code runs with minor issues, basic implementation | Canvas API attempted but code has errors or doesn't execute |
|
||||
| **Creativity and Design** | Highly original concept with polished visual appeal, demonstrates deep exploration of chosen Canvas feature | Good use of Canvas features with some creative elements, solid visual result | Basic implementation with minimal creativity or visual appeal |
|
||||
| **Code Quality** | Well-organized, commented code following best practices, efficient algorithms | Clean code with some comments, follows basic coding standards | Code lacks organization, minimal comments, inefficient implementation |
|
||||
|
||||
## Reflection Questions
|
||||
|
||||
After completing your project, consider these questions:
|
||||
|
||||
1. **What Canvas API feature did you choose and why?**
|
||||
2. **What challenges did you encounter while building your project?**
|
||||
3. **How could you extend this project into a larger application or game?**
|
||||
4. **What other Canvas API features would you like to explore next?**
|
||||
|
||||
> 💡 **Pro Tip**: Start simple and gradually add complexity. A well-executed simple project is better than an overly ambitious project that doesn't work properly!
|
||||
@ -1,19 +1,157 @@
|
||||
# Build a Sample Game
|
||||
|
||||
## Instructions
|
||||
## Assignment Overview
|
||||
|
||||
Try building a small game where you practice on different end conditions. Vary between getting a number of points, the hero loses all lives or all monsters are defeated. Build something simple like a console based adventure game. Use the below game flow as inspiration:
|
||||
Now that you've mastered game end conditions and restart functionality in your space game, it's time to apply these concepts to a completely new gaming experience. You'll design and build your own game that demonstrates different end condition patterns and restart mechanics.
|
||||
|
||||
This assignment challenges you to think creatively about game design while practicing the technical skills you've learned. You'll explore different victory and defeat scenarios, implement player progression, and create engaging restart experiences.
|
||||
|
||||
## Project Requirements
|
||||
|
||||
### Core Game Features
|
||||
|
||||
Your game must include the following essential elements:
|
||||
|
||||
**End Condition Variety**: Implement at least two different ways the game can end:
|
||||
- **Point-based victory**: Player reaches a target score or collects specific items
|
||||
- **Life-based defeat**: Player loses all available lives or health points
|
||||
- **Objective completion**: All enemies defeated, specific items collected, or goals achieved
|
||||
- **Time-based**: Game ends after a set duration or countdown reaches zero
|
||||
|
||||
**Restart Functionality**:
|
||||
- **Clear game state**: Remove all previous game objects and reset variables
|
||||
- **Reinitialize systems**: Start fresh with new player stats, enemies, and objectives
|
||||
- **User-friendly controls**: Provide clear instructions for restarting the game
|
||||
|
||||
**Player Feedback**:
|
||||
- **Victory messages**: Celebrate player achievements with positive feedback
|
||||
- **Defeat messages**: Provide encouraging messages that motivate replay
|
||||
- **Progress indicators**: Show current score, lives, or objective status
|
||||
|
||||
### Game Ideas and Inspiration
|
||||
|
||||
Choose one of these game concepts or create your own:
|
||||
|
||||
#### 1. Console Adventure Game
|
||||
Create a text-based adventure with combat mechanics:
|
||||
|
||||
```
|
||||
Hero> Strikes with broadsword - orc takes 3p damage
|
||||
Orc> Hits with club - hero takes 2p damage
|
||||
Orc> Hits with club - hero takes 2p damage
|
||||
Hero> Kicks - orc takes 1p damage
|
||||
Game> Orc is defeated - Hero collects 2 coins
|
||||
Game> ****No more monsters, you have conquered the evil fortress****
|
||||
```
|
||||
|
||||
## Rubric
|
||||
**Key features to implement:**
|
||||
- **Turn-based combat** with different attack options
|
||||
- **Health points** for both player and enemies
|
||||
- **Inventory system** for collecting coins or items
|
||||
- **Multiple enemy types** with varying difficulty
|
||||
- **Victory condition** when all enemies are defeated
|
||||
|
||||
#### 2. Collection Game
|
||||
- **Objective**: Collect specific items while avoiding obstacles
|
||||
- **End conditions**: Reach target collection count or lose all lives
|
||||
- **Progression**: Items become harder to reach as game continues
|
||||
|
||||
#### 3. Puzzle Game
|
||||
- **Objective**: Solve increasingly difficult puzzles
|
||||
- **End conditions**: Complete all levels or run out of moves/time
|
||||
- **Restart**: Reset to first level with cleared progress
|
||||
|
||||
#### 4. Defense Game
|
||||
- **Objective**: Protect your base from waves of enemies
|
||||
- **End conditions**: Survive all waves (victory) or base is destroyed (defeat)
|
||||
- **Progression**: Enemy waves increase in difficulty and number
|
||||
|
||||
## Implementation Guidelines
|
||||
|
||||
### Getting Started
|
||||
|
||||
1. **Plan your game design**:
|
||||
- Sketch the basic gameplay loop
|
||||
- Define your end conditions clearly
|
||||
- Identify what data needs to be reset on restart
|
||||
|
||||
2. **Set up your project structure**:
|
||||
```
|
||||
my-game/
|
||||
├── index.html
|
||||
├── style.css
|
||||
├── game.js
|
||||
└── README.md
|
||||
```
|
||||
|
||||
3. **Create your core game loop**:
|
||||
- Initialize game state
|
||||
- Handle user input
|
||||
- Update game logic
|
||||
- Check end conditions
|
||||
- Render current state
|
||||
|
||||
### Technical Requirements
|
||||
|
||||
**Use Modern JavaScript**:
|
||||
- Apply `const` and `let` for variable declarations
|
||||
- Use arrow functions where appropriate
|
||||
- Implement ES6+ features like template literals and destructuring
|
||||
|
||||
**Event-Driven Architecture**:
|
||||
- Create event handlers for user interactions
|
||||
- Implement game state changes through events
|
||||
- Use event listeners for restart functionality
|
||||
|
||||
**Clean Code Practices**:
|
||||
- Write functions with single responsibilities
|
||||
- Use descriptive variable and function names
|
||||
- Add comments explaining game logic and rules
|
||||
- Organize code into logical sections
|
||||
|
||||
## Submission Requirements
|
||||
|
||||
### Deliverables
|
||||
|
||||
1. **Complete game files**: All HTML, CSS, and JavaScript files needed to run your game
|
||||
2. **README.md**: Documentation explaining:
|
||||
- How to play your game
|
||||
- What end conditions you implemented
|
||||
- Instructions for restarting
|
||||
- Any special features or mechanics
|
||||
3. **Code comments**: Clear explanations of your game logic and algorithms
|
||||
|
||||
### Testing Checklist
|
||||
|
||||
Before submitting, verify that your game:
|
||||
|
||||
- [ ] **Runs without errors** in the browser console
|
||||
- [ ] **Implements multiple end conditions** as specified
|
||||
- [ ] **Restarts properly** with clean state reset
|
||||
- [ ] **Provides clear feedback** to players about game status
|
||||
- [ ] **Uses modern JavaScript** syntax and best practices
|
||||
- [ ] **Includes comprehensive documentation** in README.md
|
||||
|
||||
## Assessment Rubric
|
||||
|
||||
| Criteria | Exemplary (4) | Proficient (3) | Developing (2) | Beginning (1) |
|
||||
|----------|---------------|----------------|----------------|--------------|
|
||||
| **Game Functionality** | Complete game with multiple end conditions, smooth restart, and polished gameplay experience | Full game with basic end conditions and functional restart mechanism | Partial game with some end conditions implemented, restart may have minor issues | Incomplete game with limited functionality and significant bugs |
|
||||
| **Code Quality** | Clean, well-organized code using modern JavaScript practices, comprehensive comments, and excellent structure | Good code organization with modern syntax, adequate comments, and clear structure | Basic code organization with some modern practices, minimal comments | Poor code organization, outdated syntax, lacking comments and structure |
|
||||
| **User Experience** | Intuitive gameplay with clear instructions, excellent feedback, and engaging end/restart experience | Good gameplay with adequate instructions and feedback, functional end/restart | Basic gameplay with minimal instructions, limited feedback on game state | Confusing gameplay with unclear instructions and poor user feedback |
|
||||
| **Technical Implementation** | Demonstrates mastery of game development concepts, event handling, and state management | Shows solid understanding of game concepts with good implementation | Basic understanding with acceptable implementation | Limited understanding with poor implementation |
|
||||
| **Documentation** | Comprehensive README with clear instructions, well-documented code, and thorough testing evidence | Good documentation with clear instructions and adequate code comments | Basic documentation with minimal instructions | Poor or missing documentation |
|
||||
|
||||
### Grading Scale
|
||||
- **Exemplary (16-20 points)**: Exceeds expectations with creative features and polished implementation
|
||||
- **Proficient (12-15 points)**: Meets all requirements with solid execution
|
||||
- **Developing (8-11 points)**: Meets most requirements with minor issues
|
||||
- **Beginning (4-7 points)**: Meets some requirements but needs significant improvement
|
||||
|
||||
## Additional Learning Resources
|
||||
|
||||
- [MDN Game Development Guide](https://developer.mozilla.org/en-US/docs/Games)
|
||||
- [JavaScript Game Development Tutorials](https://developer.mozilla.org/en-US/docs/Games/Tutorials)
|
||||
- [Canvas API Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
|
||||
- [Game Design Principles](https://www.gamasutra.com/blogs/)
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ---------------------- | --------------------------- | -------------------------- |
|
||||
| | full game is presented | game is partially presented | partial game contains bugs |
|
||||
> 💡 **Pro Tip**: Start simple and add features incrementally. A well-polished simple game is better than a complex game with bugs!
|
||||
@ -1,13 +1,150 @@
|
||||
# Style your bank app
|
||||
# Style Your Bank App with Modern CSS
|
||||
|
||||
## Project Overview
|
||||
|
||||
Transform your functional banking application into a visually appealing, professional-looking web app using modern CSS techniques. You'll create a cohesive design system that enhances user experience while maintaining accessibility and responsive design principles.
|
||||
|
||||
This assignment challenges you to apply contemporary web design patterns, implement a consistent visual identity, and create an interface that users will find both attractive and intuitive to navigate.
|
||||
|
||||
## Instructions
|
||||
|
||||
Create a new `styles.css` file and add a link to it in your current `index.html` file. In the CSS file you just created add some styling to make the *Login* and *Dashboard* page looks nice and tidy. Try to create a color theme to give your app its own branding.
|
||||
### Step 1: Setup Your Stylesheet
|
||||
|
||||
**Create your CSS foundation:**
|
||||
|
||||
1. **Create** a new file called `styles.css` in your project root
|
||||
2. **Link** the stylesheet in your `index.html` file:
|
||||
```html
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
```
|
||||
3. **Start** with CSS reset and modern defaults:
|
||||
```css
|
||||
/* Modern CSS reset and base styles */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Design System Requirements
|
||||
|
||||
**Implement these essential design elements:**
|
||||
|
||||
#### Color Palette
|
||||
- **Primary color**: Choose a professional color for buttons and highlights
|
||||
- **Secondary color**: Complementary color for accents and secondary actions
|
||||
- **Neutral colors**: Grays for text, borders, and backgrounds
|
||||
- **Success/Error colors**: Green for success states, red for errors
|
||||
|
||||
#### Typography
|
||||
- **Heading hierarchy**: Clear distinction between H1, H2, and H3 elements
|
||||
- **Body text**: Readable font size (minimum 16px) and appropriate line height
|
||||
- **Form labels**: Clear, accessible text styling
|
||||
|
||||
#### Layout and Spacing
|
||||
- **Consistent spacing**: Use a spacing scale (8px, 16px, 24px, 32px)
|
||||
- **Grid system**: Organized layout for forms and content sections
|
||||
- **Responsive design**: Mobile-first approach with breakpoints
|
||||
|
||||
### Step 3: Component Styling
|
||||
|
||||
**Style these specific components:**
|
||||
|
||||
#### Forms
|
||||
- **Input fields**: Professional borders, focus states, and validation styling
|
||||
- **Buttons**: Hover effects, disabled states, and loading indicators
|
||||
- **Labels**: Clear positioning and required field indicators
|
||||
- **Error messages**: Visible error styling and helpful messaging
|
||||
|
||||
#### Navigation
|
||||
- **Header**: Clean, branded navigation area
|
||||
- **Links**: Clear hover states and active indicators
|
||||
- **Logo/Title**: Distinctive branding element
|
||||
|
||||
#### Content Areas
|
||||
- **Sections**: Clear visual separation between different areas
|
||||
- **Cards**: If using card-based layouts, include shadows and borders
|
||||
- **Backgrounds**: Appropriate use of white space and subtle backgrounds
|
||||
|
||||
### Step 4: Enhanced Features (Optional)
|
||||
|
||||
**Consider implementing these advanced features:**
|
||||
- **Dark mode**: Toggle between light and dark themes
|
||||
- **Animations**: Subtle transitions and micro-interactions
|
||||
- **Loading states**: Visual feedback during form submissions
|
||||
- **Responsive images**: Optimized images for different screen sizes
|
||||
|
||||
## Design Inspiration
|
||||
|
||||
**Modern banking app characteristics:**
|
||||
- **Clean, minimal design** with plenty of white space
|
||||
- **Professional color schemes** (blues, greens, or sophisticated neutrals)
|
||||
- **Clear visual hierarchy** with prominent call-to-action buttons
|
||||
- **Accessible contrast ratios** meeting WCAG guidelines
|
||||
- **Mobile-responsive layouts** that work on all devices
|
||||
|
||||
## Technical Requirements
|
||||
|
||||
### CSS Organization
|
||||
```css
|
||||
/* 1. CSS Custom Properties (Variables) */
|
||||
:root {
|
||||
--primary-color: #007bff;
|
||||
--secondary-color: #6c757d;
|
||||
/* Add more variables */
|
||||
}
|
||||
|
||||
/* 2. Base Styles */
|
||||
/* Reset, typography, general elements */
|
||||
|
||||
/* 3. Layout */
|
||||
/* Grid, flexbox, positioning */
|
||||
|
||||
/* 4. Components */
|
||||
/* Forms, buttons, cards */
|
||||
|
||||
/* 5. Utilities */
|
||||
/* Helper classes, responsive utilities */
|
||||
|
||||
/* 6. Media Queries */
|
||||
/* Responsive breakpoints */
|
||||
```
|
||||
|
||||
### Accessibility Requirements
|
||||
- **Color contrast**: Ensure at least 4.5:1 ratio for normal text
|
||||
- **Focus indicators**: Visible focus states for keyboard navigation
|
||||
- **Form labels**: Properly associated with inputs
|
||||
- **Responsive design**: Usable on screens from 320px to 1920px wide
|
||||
|
||||
## Evaluation Rubric
|
||||
|
||||
| Criteria | Exemplary (A) | Proficient (B) | Developing (C) | Needs Improvement (F) |
|
||||
|----------|---------------|----------------|----------------|----------------------|
|
||||
| **Design System** | Implements comprehensive design system with consistent colors, typography, and spacing throughout | Uses consistent styling with clear design patterns and good visual hierarchy | Basic styling applied with some consistency issues or missing design elements | Minimal styling with inconsistent or conflicting design choices |
|
||||
| **User Experience** | Creates intuitive, professional interface with excellent usability and visual appeal | Provides good user experience with clear navigation and readable content | Basic usability with some UX improvements needed | Poor usability, difficult to navigate or read |
|
||||
| **Technical Implementation** | Uses modern CSS techniques, organized code structure, and follows best practices | Implements CSS effectively with good organization and appropriate techniques | CSS works correctly but may lack organization or modern approaches | Poor CSS implementation with technical issues or browser compatibility problems |
|
||||
| **Responsive Design** | Fully responsive design that works beautifully across all device sizes | Good responsive behavior with minor issues on some screen sizes | Basic responsive implementation with some layout issues | Not responsive or significant problems on mobile devices |
|
||||
| **Accessibility** | Meets WCAG guidelines with excellent keyboard navigation and screen reader support | Good accessibility practices with proper contrast and focus indicators | Basic accessibility considerations with some missing elements | Poor accessibility, difficult for users with disabilities |
|
||||
|
||||
## Submission Guidelines
|
||||
|
||||
> Tip: you can modify the HTML and add new elements and classes if needed.
|
||||
**Include in your submission:**
|
||||
- **styles.css**: Your complete stylesheet
|
||||
- **Updated HTML**: Any HTML modifications you made
|
||||
- **Screenshots**: Images showing your design on desktop and mobile
|
||||
- **README**: Brief description of your design choices and color palette
|
||||
|
||||
## Rubric
|
||||
**Bonus points for:**
|
||||
- **CSS custom properties** for maintainable theming
|
||||
- **Advanced CSS features** like Grid, Flexbox, or CSS animations
|
||||
- **Performance considerations** like optimized CSS and minimal file size
|
||||
- **Cross-browser testing** ensuring compatibility across different browsers
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
|
||||
| | All pages looks clean and readable, with a consistent color theme and and the different sections standing out properly. | Pages are styled but without a theme or with sections not clearly delimitated. | Pages lack styling, the sections looks disorganized and the information is difficult to read. |
|
||||
> 💡 **Pro Tip**: Start with mobile design first, then enhance for larger screens. This mobile-first approach ensures your app works well on all devices and follows modern web development best practices.
|
||||
@ -1,15 +1,128 @@
|
||||
# Refactor and comment your code
|
||||
# Code Refactoring and Documentation Assignment
|
||||
|
||||
## Learning Objectives
|
||||
|
||||
By completing this assignment, you will practice essential software development skills that professional developers use daily. You'll learn to organize code for maintainability, reduce duplication through abstraction, and document your work for future developers (including yourself!).
|
||||
|
||||
Clean, well-documented code is crucial for real-world web development projects where multiple developers collaborate and codebases evolve over time.
|
||||
|
||||
## Assignment Overview
|
||||
|
||||
Your banking app's `app.js` file has grown significantly with login, registration, and dashboard functionality. It's time to refactor this code using professional development practices to improve readability, maintainability, and reduce duplication.
|
||||
|
||||
## Instructions
|
||||
|
||||
As your codebase grows, it's important to refactor your code frequently to keep it readable and maintainable over time. Add comments and refactor your `app.js` to improve the code quality:
|
||||
Transform your current `app.js` code by implementing these three core refactoring techniques:
|
||||
|
||||
### 1. Extract Configuration Constants
|
||||
|
||||
**Task**: Create a configuration section at the top of your file with reusable constants.
|
||||
|
||||
**Implementation guidance:**
|
||||
- Extract the server API base URL (currently hardcoded in multiple places)
|
||||
- Create constants for error messages that appear in multiple functions
|
||||
- Consider extracting route paths and element IDs that are used repeatedly
|
||||
|
||||
**Example structure:**
|
||||
```javascript
|
||||
// Configuration constants
|
||||
const API_BASE_URL = 'http://localhost:5000/api';
|
||||
const ROUTES = {
|
||||
LOGIN: '/login',
|
||||
DASHBOARD: '/dashboard'
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Create a Unified Request Function
|
||||
|
||||
**Task**: Build a reusable `sendRequest()` function that eliminates duplicate code between `createAccount()` and `getAccount()`.
|
||||
|
||||
**Requirements:**
|
||||
- Handle both GET and POST requests
|
||||
- Include proper error handling
|
||||
- Support different URL endpoints
|
||||
- Accept optional request body data
|
||||
|
||||
**Function signature guidance:**
|
||||
```javascript
|
||||
async function sendRequest(endpoint, method = 'GET', data = null) {
|
||||
// Your implementation here
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Add Professional Code Documentation
|
||||
|
||||
**Task**: Document your code with clear, helpful comments that explain the "why" behind your logic.
|
||||
|
||||
**Documentation standards:**
|
||||
- Add function documentation explaining purpose, parameters, and return values
|
||||
- Include inline comments for complex logic or business rules
|
||||
- Group related functions together with section headers
|
||||
- Explain any non-obvious code patterns or browser-specific workarounds
|
||||
|
||||
**Example documentation style:**
|
||||
```javascript
|
||||
/**
|
||||
* Authenticates user and redirects to dashboard
|
||||
* @param {Event} event - Form submission event
|
||||
* @returns {Promise<void>} - Resolves when login process completes
|
||||
*/
|
||||
async function login(event) {
|
||||
// Prevent default form submission to handle with JavaScript
|
||||
event.preventDefault();
|
||||
|
||||
// Your implementation...
|
||||
}
|
||||
```
|
||||
|
||||
## Success Criteria
|
||||
|
||||
Your refactored code should demonstrate these professional development practices:
|
||||
|
||||
### Exemplary Implementation
|
||||
- ✅ **Constants**: All magic strings and URLs are extracted into clearly named constants
|
||||
- ✅ **DRY Principle**: Common request logic is consolidated into a reusable `sendRequest()` function
|
||||
- ✅ **Documentation**: Functions have clear JSDoc comments explaining purpose and parameters
|
||||
- ✅ **Organization**: Code is logically grouped with section headers and consistent formatting
|
||||
- ✅ **Error Handling**: Improved error handling using the new request function
|
||||
|
||||
### Adequate Implementation
|
||||
- ✅ **Constants**: Most repeated values are extracted, with minor hardcoded values remaining
|
||||
- ✅ **Factorization**: Basic `sendRequest()` function created but may not handle all edge cases
|
||||
- ✅ **Comments**: Key functions are documented, though some explanations could be more complete
|
||||
- ✅ **Readability**: Code is generally well-organized with some areas for improvement
|
||||
|
||||
### Needs Improvement
|
||||
- ❌ **Constants**: Many magic strings and URLs remain hardcoded throughout the file
|
||||
- ❌ **Duplication**: Significant code duplication remains between similar functions
|
||||
- ❌ **Documentation**: Missing or inadequate comments that don't explain the code's purpose
|
||||
- ❌ **Organization**: Code lacks clear structure and logical grouping
|
||||
|
||||
## Testing Your Refactored Code
|
||||
|
||||
After refactoring, ensure your banking app still functions correctly:
|
||||
|
||||
1. **Test all user flows**: Registration, login, dashboard display, and error handling
|
||||
2. **Verify API calls**: Confirm that your `sendRequest()` function works for both account creation and retrieval
|
||||
3. **Check error scenarios**: Test with invalid credentials and network errors
|
||||
4. **Review console output**: Ensure no new errors were introduced during refactoring
|
||||
|
||||
## Submission Guidelines
|
||||
|
||||
Submit your refactored `app.js` file with:
|
||||
- Clear section headers organizing different functionality
|
||||
- Consistent code formatting and indentation
|
||||
- Complete JSDoc documentation for all functions
|
||||
- A brief comment at the top explaining your refactoring approach
|
||||
|
||||
**Bonus Challenge**: Create a simple code documentation file (`CODE_STRUCTURE.md`) that explains your app's architecture and how the different functions work together.
|
||||
|
||||
- Extract constants, like the server API base URL
|
||||
- Factorize similar code: for example you can create a `sendRequest()` function to regroup the code used in both `createAccount()` and `getAccount()`
|
||||
- Reorganize the code to make it easier to read, and add comments
|
||||
## Real-World Connection
|
||||
|
||||
## Rubric
|
||||
This assignment mirrors the type of code maintenance that professional developers perform regularly. In industry settings:
|
||||
- **Code reviews** evaluate readability and maintainability like this assignment
|
||||
- **Technical debt** accumulates when code isn't regularly refactored and documented
|
||||
- **Team collaboration** depends on clear, well-documented code that new team members can understand
|
||||
- **Bug fixes** are much easier in well-organized codebases with proper abstractions
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| | Code is commented, well-organized in different sections and easy to read. Constants are extracted and a factorized `sendRequest()` function has been created. | Code is clean but can still be improved with more comments, constant extraction or factorization. | Code is messy, not commented, constants are not extracted and code is not factorized. |
|
||||
The skills you're practicing here - extracting constants, eliminating duplication, and writing clear documentation - are fundamental to professional software development.
|
||||
|
||||
@ -1,25 +1,148 @@
|
||||
# Implement "Add transaction" dialog
|
||||
# Implement "Add Transaction" Dialog
|
||||
|
||||
## Overview
|
||||
|
||||
Your banking app now has solid state management and data persistence, but it's missing a crucial feature that real banking apps need: the ability for users to add their own transactions. In this assignment, you'll implement a complete "Add Transaction" dialog that integrates seamlessly with your existing state management system.
|
||||
|
||||
This assignment brings together everything you've learned in the four banking lessons: HTML templating, form handling, API integration, and state management.
|
||||
|
||||
## Learning Objectives
|
||||
|
||||
By completing this assignment, you will:
|
||||
- **Create** a user-friendly dialog interface for data entry
|
||||
- **Implement** accessible form design with keyboard and screen reader support
|
||||
- **Integrate** new features with your existing state management system
|
||||
- **Practice** API communication and error handling
|
||||
- **Apply** modern web development patterns to a real-world feature
|
||||
|
||||
## Instructions
|
||||
|
||||
Our bank app is still missing one important feature: the possibility to enter new transactions.
|
||||
Using everything that you've learnt in the four previous lessons, implement an "Add transaction" dialog:
|
||||
### Step 1: Add Transaction Button
|
||||
|
||||
**Create** an "Add Transaction" button on your dashboard page that users can easily find and access.
|
||||
|
||||
**Requirements:**
|
||||
- **Place** the button in a logical location on the dashboard
|
||||
- **Use** clear, action-oriented button text
|
||||
- **Style** the button to match your existing UI design
|
||||
- **Ensure** the button is keyboard accessible
|
||||
|
||||
### Step 2: Dialog Implementation
|
||||
|
||||
Choose one of these two approaches for implementing your dialog:
|
||||
|
||||
**Option A: Separate Page**
|
||||
- **Create** a new HTML template for the transaction form
|
||||
- **Add** a new route to your routing system
|
||||
- **Implement** navigation to and from the form page
|
||||
|
||||
**Option B: Modal Dialog (Recommended)**
|
||||
- **Use** JavaScript to show/hide the dialog without leaving the dashboard
|
||||
- **Implement** using the [`hidden` property](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/hidden) or CSS classes
|
||||
- **Create** a smooth user experience with proper focus management
|
||||
|
||||
### Step 3: Accessibility Implementation
|
||||
|
||||
**Ensure** your dialog meets [accessibility standards for modal dialogs](https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/):
|
||||
|
||||
**Keyboard Navigation:**
|
||||
- **Support** Escape key to close the dialog
|
||||
- **Trap** focus within the dialog when open
|
||||
- **Return** focus to the trigger button when closed
|
||||
|
||||
**Screen Reader Support:**
|
||||
- **Add** appropriate ARIA labels and roles
|
||||
- **Announce** dialog opening/closing to screen readers
|
||||
- **Provide** clear form field labels and error messages
|
||||
|
||||
### Step 4: Form Creation
|
||||
|
||||
**Design** an HTML form that collects transaction data:
|
||||
|
||||
- Add an "Add transaction" button in the dashboard page
|
||||
- Either create a new page with an HTML template, or use JavaScript to show/hide the dialog HTML without leaving the dashboard page (you can use [`hidden`](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/hidden) property for that, or CSS classes)
|
||||
- Make sure you handle [keyboard and screen reader accessibility](https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/) for the dialog
|
||||
- Implement an HTML form to receive input data
|
||||
- Create JSON data from the form data and send it to the API
|
||||
- Update the dashboard page with the new data
|
||||
**Required Fields:**
|
||||
- **Date**: When the transaction occurred
|
||||
- **Description**: What the transaction was for
|
||||
- **Amount**: Transaction value (positive for income, negative for expenses)
|
||||
|
||||
Look at the [server API specifications](../api/README.md) to see which API you need to call and what is the expected JSON format.
|
||||
**Form Features:**
|
||||
- **Validate** user input before submission
|
||||
- **Provide** clear error messages for invalid data
|
||||
- **Include** helpful placeholder text and labels
|
||||
- **Style** consistently with your existing design
|
||||
|
||||
Here's an example result after completing the assignment:
|
||||
### Step 5: API Integration
|
||||
|
||||
**Connect** your form to the backend API:
|
||||
|
||||
**Implementation Steps:**
|
||||
- **Review** the [server API specifications](../api/README.md) for the correct endpoint and data format
|
||||
- **Create** JSON data from your form inputs
|
||||
- **Send** the data to the API using appropriate error handling
|
||||
- **Display** success/failure messages to the user
|
||||
- **Handle** network errors gracefully
|
||||
|
||||
### Step 6: State Management Integration
|
||||
|
||||
**Update** your dashboard with the new transaction:
|
||||
|
||||
**Integration Requirements:**
|
||||
- **Refresh** the account data after successful transaction addition
|
||||
- **Update** the dashboard display without requiring a page reload
|
||||
- **Ensure** the new transaction appears immediately
|
||||
- **Maintain** proper state consistency throughout the process
|
||||
|
||||
## Technical Specifications
|
||||
|
||||
**API Endpoint Details:**
|
||||
Refer to the [server API documentation](../api/README.md) for:
|
||||
- Required JSON format for transaction data
|
||||
- HTTP method and endpoint URL
|
||||
- Expected response format
|
||||
- Error response handling
|
||||
|
||||
**Expected Result:**
|
||||
After completing this assignment, your banking app should have a fully functional "Add Transaction" feature that looks and behaves professionally:
|
||||
|
||||

|
||||
|
||||
## Rubric
|
||||
## Testing Your Implementation
|
||||
|
||||
**Functional Testing:**
|
||||
1. **Verify** the "Add Transaction" button is clearly visible and accessible
|
||||
2. **Test** that the dialog opens and closes properly
|
||||
3. **Confirm** form validation works for all required fields
|
||||
4. **Check** that successful transactions appear immediately on the dashboard
|
||||
5. **Ensure** error handling works for invalid data and network issues
|
||||
|
||||
**Accessibility Testing:**
|
||||
1. **Navigate** through the entire flow using only the keyboard
|
||||
2. **Test** with a screen reader to ensure proper announcements
|
||||
3. **Verify** focus management works correctly
|
||||
4. **Check** that all form elements have appropriate labels
|
||||
|
||||
## Evaluation Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | --------- | -------- | ----------------- |
|
||||
| **Functionality** | Add transaction feature works flawlessly with excellent user experience and follows all best practices from the lessons | Add transaction feature works correctly but may not follow some best practices or has minor usability issues | Add transaction feature is partially working or has significant usability problems |
|
||||
| **Code Quality** | Code is well-organized, follows established patterns, includes proper error handling, and integrates seamlessly with existing state management | Code works but may have some organization issues or inconsistent patterns with the existing codebase | Code has significant structural issues or doesn't integrate well with existing patterns |
|
||||
| **Accessibility** | Full keyboard navigation support, screen reader compatibility, and follows WCAG guidelines with excellent focus management | Basic accessibility features implemented but may be missing some keyboard navigation or screen reader features | Limited or no accessibility considerations implemented |
|
||||
| **User Experience** | Intuitive, polished interface with clear feedback, smooth interactions, and professional appearance | Good user experience with minor areas for improvement in feedback or visual design | Poor user experience with confusing interface or lack of user feedback |
|
||||
|
||||
## Additional Challenges (Optional)
|
||||
|
||||
Once you've completed the basic requirements, consider these enhancements:
|
||||
|
||||
**Enhanced Features:**
|
||||
- **Add** transaction categories (food, transportation, entertainment, etc.)
|
||||
- **Implement** input validation with real-time feedback
|
||||
- **Create** keyboard shortcuts for power users
|
||||
- **Add** transaction editing and deletion capabilities
|
||||
|
||||
**Advanced Integration:**
|
||||
- **Implement** undo functionality for recently added transactions
|
||||
- **Add** bulk transaction import from CSV files
|
||||
- **Create** transaction search and filtering capabilities
|
||||
- **Implement** data export functionality
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------|
|
||||
| | Adding a transaction is implemented completely following all best practices seen in the lessons. | Adding a transaction is implement, but not following the best practices seen in the lessons, or working only partially. | Adding a transaction is not working at all. |
|
||||
These optional features will help you practice more advanced web development concepts and create a more complete banking application!
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,56 +1,84 @@
|
||||
from flask import Flask, request, jsonify
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
from llm import call_llm
|
||||
from flask_cors import CORS
|
||||
import logging
|
||||
|
||||
app = Flask(__name__)
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Create FastAPI application
|
||||
app = FastAPI(
|
||||
title="AI Chat API",
|
||||
description="A high-performance API for AI-powered chat applications",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# Configure CORS (allow all origins for development; restrict in production)
|
||||
CORS(app, resources={r"/*": {"origins": "*"}})
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Set up logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
# Pydantic models for request/response validation
|
||||
class ChatMessage(BaseModel):
|
||||
message: str
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
response: str
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
service: str
|
||||
|
||||
@app.route("/", methods=["GET"])
|
||||
def index():
|
||||
@app.get("/")
|
||||
async def index():
|
||||
"""Root endpoint for API status."""
|
||||
return jsonify({
|
||||
return {
|
||||
"status": "ok",
|
||||
"message": "Welcome to the Chat Project API"
|
||||
})
|
||||
"message": "Welcome to the Chat Project API",
|
||||
"docs": "/docs",
|
||||
"health": "/health"
|
||||
}
|
||||
|
||||
@app.route("/health", methods=["GET"])
|
||||
def health():
|
||||
@app.get("/health", response_model=HealthResponse)
|
||||
async def health():
|
||||
"""Health check endpoint."""
|
||||
return jsonify({"status": "healthy"}), 200
|
||||
return HealthResponse(status="healthy", service="ai-chat-api")
|
||||
|
||||
@app.route("/test", methods=["GET"])
|
||||
def test():
|
||||
@app.get("/test")
|
||||
async def test():
|
||||
"""Simple test endpoint."""
|
||||
return jsonify({"result": "Test successful"}), 200
|
||||
return {"result": "Test successful"}
|
||||
|
||||
@app.route("/hello", methods=["POST"])
|
||||
def hello():
|
||||
@app.post("/hello", response_model=ChatResponse)
|
||||
async def hello(chat_message: ChatMessage):
|
||||
"""
|
||||
Chat endpoint.
|
||||
Expects JSON: { "message": "your message" }
|
||||
Returns: { "response": "LLM response" }
|
||||
"""
|
||||
try:
|
||||
data = request.get_json(force=True)
|
||||
message = data.get("message", "").strip()
|
||||
message = chat_message.message.strip()
|
||||
if not message:
|
||||
logging.warning("No message provided in request.")
|
||||
return jsonify({"error": "No message provided."}), 400
|
||||
logger.warning("Empty message provided in request.")
|
||||
raise HTTPException(status_code=400, detail="Message cannot be empty")
|
||||
|
||||
logging.info(f"Received message: {message}")
|
||||
logger.info(f"Received message: {message}")
|
||||
response = call_llm(message, "You are a helpful assistant.")
|
||||
return jsonify({"response": response}), 200
|
||||
logger.info("LLM response generated successfully")
|
||||
return ChatResponse(response=response)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logging.error(f"Error in /hello endpoint: {e}")
|
||||
return jsonify({"error": "Internal server error."}), 500
|
||||
logger.error(f"Error in /hello endpoint: {e}")
|
||||
raise HTTPException(status_code=500, detail="Internal server error")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the app with debug mode for development
|
||||
app.run(host="0.0.0.0", port=5000, debug=True)
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=5000, reload=True)
|
||||
Loading…
Reference in new issue