Blog

Demo

Basic

  1. WAP to read 2 numbers and print addition
  2. WAP to read 2 numbers and print subtraction
  3. WAP to read 2 numbers and print multiplication
  4. WAP to read 2 numbers and print division
  5. WAP to read 2 numbers and print modulus (Remainder)
  6. WAP to read radius and print area and circumference of circle
  7. WAP to read length and breadth and print area and perimeter of rectangle

Conditional Statement (if else)

  1. WAP to read a number and check if its positive or negative
  2. WAP to read a number and check it is even or odd
  3. WAP to read 2 numbers and find greatest among them
  4. WAP to read 3 numbers and find greatest among them
  5. WAP to read marks of 5 subjects and check the student is pass or failed
    1. add validation for marks less than 0
    2. add validation for marks greater than 100

Loops

  1. WAP to print hello world 10 times with numbering
  2. WAP to print square of numbers from 1 to 10
  3. WAP to print numbers from 1 to given number
  4. WAP to print cube of numbers from 1 to given number
  5. WAP to read a number and print table of that number
  6. WAP to execute Fizz Buzz Problem / Print number 1 to 100
    1. if number is divisible by 3 then print Fizz
    2. if number is divisible by 5 then print Buzz
    3. if number is divisible by both 3 and 5 then print Fizz Buzz
  7. WAP to execute lift program of 20 floor
    1. print number with delay of 1 sec (use time module’s sleep method)
    2. skip 13 number
    3. break after printing 13
  8. WAP to create random jackpot number and take input from user to guess the number. Based on level the attempt to guess the number should change
    1. Easy – 20 attempts
    2. Medium – 10 attempts
    3. Difficult – 5 attempts

Plan of Action

Programming Fundamentals Curriculum

A comprehensive guide covering JavaScript, Java, Python, and Node.js

Table of Contents

  1. Basic Syntax & Variables
  2. If-Else Statements
  3. For Loops
  4. Arrays
  5. Array of JSON Objects

1. Basic Syntax & Variables

Concept Overview

Variables are containers that store data values. Each programming language has its own syntax for declaring and using variables.

Syntax Comparison

JavaScript:

// Variable declaration
let name = "John";
const age = 25;
var city = "New York"; // older syntax

// Data types
let number = 42;
let text = "Hello World";
let isActive = true;
let items = null;

Java:

// Variable declaration with type specification
String name = "John";
final int age = 25; // final = constant
int number = 42;
boolean isActive = true;

Python:

# Dynamic typing - no need to specify type
name = "John"
age = 25  # Numbers can be changed later
number = 42
text = "Hello World"
is_active = True  # Note: True/False capitalized

Node.js:

// Same as JavaScript (Node.js runs JavaScript)
const name = "John";
let age = 25;
console.log(`Hello ${name}, you are ${age} years old`);

Example 1: Basic Calculator

JavaScript:

let num1 = 10;
let num2 = 5;
let sum = num1 + num2;
console.log("Sum: " + sum);

Java:

public class Calculator {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 5;
        int sum = num1 + num2;
        System.out.println("Sum: " + sum);
    }
}

Python:

num1 = 10
num2 = 5
sum = num1 + num2
print(f"Sum: {sum}")

Example 2: User Profile

JavaScript:

const firstName = "Alice";
const lastName = "Johnson";
let age = 28;
let fullName = firstName + " " + lastName;
console.log(`Profile: ${fullName}, Age: ${age}`);

Python:

first_name = "Alice"
last_name = "Johnson"
age = 28
full_name = first_name + " " + last_name
print(f"Profile: {full_name}, Age: {age}")

Classwork 1: Personal Information

Create variables to store your personal information and display them:

  • Full name (combine first and last name)
  • Age
  • Favorite color
  • Current year
  • Calculate birth year using current year and age

Classwork 2: Shopping Calculator

Create a program that calculates the total cost of shopping:

  • Item price
  • Quantity
  • Tax rate (8%)
  • Calculate total cost including tax

Classwork 3: Temperature Converter

Create variables to convert temperature from Celsius to Fahrenheit:

  • Celsius temperature
  • Apply formula: F = (C × 9/5) + 32
  • Display both temperatures

Assignments

Assignment 1: Student Grade Calculator Create a program that stores a student’s information and calculates their average grade:

  • Student name
  • Three subject scores (Math, Science, English)
  • Calculate average
  • Display student name and average grade

Assignment 2: Rectangle Area and Perimeter Write a program that calculates the area and perimeter of a rectangle:

  • Length and width variables
  • Calculate area (length × width)
  • Calculate perimeter (2 × (length + width))
  • Display all values with appropriate labels

Assignment 3: Time Converter Create a program that converts time:

  • Total seconds as input
  • Convert to hours, minutes, and remaining seconds
  • Display in format “X hours, Y minutes, Z seconds”

Assignment 4: Simple Interest Calculator Calculate simple interest on a loan:

  • Principal amount
  • Interest rate (annual percentage)
  • Time period (in years)
  • Calculate simple interest = (P × R × T) / 100
  • Display principal, interest, and total amount

Assignment 5: BMI Calculator Create a Body Mass Index calculator:

  • Height in meters
  • Weight in kilograms
  • Calculate BMI = weight / (height × height)
  • Display height, weight, and BMI with appropriate messages

2. If-Else Statements

Concept Overview

Conditional statements allow programs to make decisions based on different conditions. They execute different blocks of code depending on whether conditions are true or false.

Syntax Comparison

JavaScript:

// Basic if-else
if (condition) {
    // code if true
} else if (anotherCondition) {
    // code for another condition
} else {
    // code if all conditions are false
}

// Comparison operators: ==, ===, !=, !==, <, >, <=, >=
// Logical operators: &&, ||, !

Java:

// Basic if-else
if (condition) {
    // code if true
} else if (anotherCondition) {
    // code for another condition
} else {
    // code if all conditions are false
}

// Comparison operators: ==, !=, <, >, <=, >=
// Logical operators: &&, ||, !

Python:

# Basic if-else (note the indentation and colons)
if condition:
    # code if true
elif another_condition:
    # code for another condition
else:
    # code if all conditions are false

# Comparison operators: ==, !=, <, >, <=, >=
# Logical operators: and, or, not

Example 1: Grade Classification

JavaScript:

let score = 85;
let grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade = "D";
} else {
    grade = "F";
}

console.log(`Score: ${score}, Grade: ${grade}`);

Python:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}, Grade: {grade}")

Example 2: Age Category

JavaScript:

let age = 17;
let category;

if (age < 13) {
    category = "Child";
} else if (age < 20) {
    category = "Teenager";
} else if (age < 60) {
    category = "Adult";
} else {
    category = "Senior";
}

console.log(`Age: ${age}, Category: ${category}`);

Java:

public class AgeCategory {
    public static void main(String[] args) {
        int age = 17;
        String category;
        
        if (age < 13) {
            category = "Child";
        } else if (age < 20) {
            category = "Teenager";
        } else if (age < 60) {
            category = "Adult";
        } else {
            category = "Senior";
        }
        
        System.out.println("Age: " + age + ", Category: " + category);
    }
}

Classwork 1: Number Checker

Write a program that checks if a number is:

  • Positive, negative, or zero
  • Even or odd (if not zero)
  • Display appropriate messages

Classwork 2: Login System

Create a simple login system:

  • Check if username is “admin” and password is “123456”
  • Display “Login successful” or “Invalid credentials”
  • Add a check for empty username or password

Classwork 3: Weather Recommendation

Based on temperature, recommend clothing:

  • Below 0°C: “Wear heavy coat”
  • 0-15°C: “Wear jacket”
  • 16-25°C: “Wear light clothing”
  • Above 25°C: “Wear summer clothes”

Assignments

Assignment 1: Traffic Light System Create a traffic light program:

  • Input a color (red, yellow, green)
  • Output the appropriate action (stop, caution, go)
  • Handle invalid colors with an error message

Assignment 2: Discount Calculator Create a discount system based on purchase amount:

  • $0-$99: No discount
  • $100-$499: 5% discount
  • $500-$999: 10% discount
  • $1000+: 15% discount
  • Calculate and display final amount

Assignment 3: Password Strength Checker Check password strength based on:

  • Length (minimum 8 characters)
  • Contains numbers
  • Contains uppercase letters
  • Display “Strong”, “Medium”, or “Weak”

Assignment 4: Leap Year Calculator Determine if a year is a leap year:

  • Divisible by 4 AND (not divisible by 100 OR divisible by 400)
  • Display whether the year is a leap year or not

Assignment 5: Grade Point Average Calculator Convert letter grades to GPA:

  • A = 4.0, B = 3.0, C = 2.0, D = 1.0, F = 0.0
  • Take multiple grades and calculate average GPA
  • Display GPA with classification (Excellent, Good, Average, Poor)

3. For Loops

Concept Overview

For loops allow you to repeat a block of code a specific number of times or iterate through collections of data. They’re essential for processing multiple items efficiently.

Syntax Comparison

JavaScript:

// Traditional for loop
for (let i = 0; i < 10; i++) {
    console.log(i);
}

// For...of loop (for arrays)
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
    console.log(fruit);
}

// For...in loop (for object properties)
let person = {name: "John", age: 30};
for (let key in person) {
    console.log(key + ": " + person[key]);
}

Java:

// Traditional for loop
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

// Enhanced for loop (for arrays/collections)
String[] fruits = {"apple", "banana", "orange"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

Python:

# For loop with range
for i in range(10):
    print(i)

# For loop with list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# For loop with enumeration (index and value)
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

Example 1: Multiplication Table

JavaScript:

let number = 5;
console.log(`Multiplication table for ${number}:`);

for (let i = 1; i <= 10; i++) {
    let result = number * i;
    console.log(`${number} × ${i} = ${result}`);
}

Python:

number = 5
print(f"Multiplication table for {number}:")

for i in range(1, 11):
    result = number * i
    print(f"{number} × {i} = {result}")

Java:

public class MultiplicationTable {
    public static void main(String[] args) {
        int number = 5;
        System.out.println("Multiplication table for " + number + ":");
        
        for (int i = 1; i <= 10; i++) {
            int result = number * i;
            System.out.println(number + " × " + i + " = " + result);
        }
    }
}

Example 2: Sum Calculator

JavaScript:

let numbers = [10, 20, 30, 40, 50];
let sum = 0;

console.log("Numbers:", numbers);
for (let number of numbers) {
    sum += number;
    console.log(`Adding ${number}, running total: ${sum}`);
}

console.log(`Final sum: ${sum}`);

Python:

numbers = [10, 20, 30, 40, 50]
sum_total = 0

print("Numbers:", numbers)
for number in numbers:
    sum_total += number
    print(f"Adding {number}, running total: {sum_total}")

print(f"Final sum: {sum_total}")

Classwork 1: Even Number Generator

Write a program that:

  • Uses a for loop to print all even numbers from 2 to 20
  • Calculates the sum of these even numbers
  • Displays the final sum

Classwork 2: Countdown Timer

Create a countdown program:

  • Start from 10 and count down to 1
  • Display each number with “seconds remaining”
  • Display “Blast off!” at the end

Classwork 3: Pattern Printer

Use nested for loops to print this pattern:

*
**
***
****
*****

Assignments

Assignment 1: Factorial Calculator Calculate the factorial of a number using a for loop:

  • Input: A positive integer
  • Calculate factorial (n! = 1 × 2 × 3 × … × n)
  • Display the calculation process and final result

Assignment 2: Prime Number Finder Find all prime numbers between 1 and 50:

  • Use nested loops to check if numbers are prime
  • A prime number is only divisible by 1 and itself
  • Display all prime numbers found

Assignment 3: Student Grade Processor Process grades for multiple students:

  • Use a loop to input grades for 5 students
  • Calculate each student’s average from 3 subjects
  • Find and display the highest and lowest averages

Assignment 4: Pattern Generator Create a program that prints multiple patterns:

  • Right triangle pattern with numbers
  • Inverted triangle pattern
  • Diamond pattern using stars Allow user to choose pattern type and size

Assignment 5: Sales Report Generator Generate a sales report for a week:

  • Use a loop to input daily sales for 7 days
  • Calculate total weekly sales
  • Find the best and worst sales days
  • Calculate average daily sales
  • Display a formatted report

4. Arrays

Concept Overview

Arrays are data structures that can store multiple values in a single variable. They’re fundamental for organizing and manipulating collections of data.

Syntax Comparison

JavaScript:

// Array declaration and initialization
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["text", 42, true, null];

// Accessing elements (0-indexed)
console.log(fruits[0]); // "apple"

// Array methods
fruits.push("grape");        // Add to end
fruits.pop();               // Remove from end
fruits.unshift("mango");    // Add to beginning
fruits.shift();             // Remove from beginning
console.log(fruits.length); // Get array size

Java:

// Array declaration and initialization
String[] fruits = {"apple", "banana", "orange"};
int[] numbers = {1, 2, 3, 4, 5};

// Accessing elements
System.out.println(fruits[0]); // "apple"

// Array length
System.out.println(fruits.length); // Get array size

// ArrayList for dynamic arrays
import java.util.ArrayList;
ArrayList<String> dynamicFruits = new ArrayList<>();
dynamicFruits.add("apple");
dynamicFruits.add("banana");

Python:

# List declaration and initialization
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["text", 42, True, None]

# Accessing elements
print(fruits[0])  # "apple"
print(fruits[-1]) # Last element: "orange"

# List methods
fruits.append("grape")      # Add to end
fruits.pop()               # Remove from end
fruits.insert(0, "mango")  # Insert at position
fruits.remove("banana")    # Remove by value
print(len(fruits))         # Get list size

Example 1: Shopping List Manager

JavaScript:

let shoppingList = ["milk", "bread", "eggs", "butter"];

console.log("Original shopping list:");
for (let i = 0; i < shoppingList.length; i++) {
    console.log(`${i + 1}. ${shoppingList[i]}`);
}

// Add new items
shoppingList.push("cheese", "apples");

// Remove first item
shoppingList.shift();

console.log("\nUpdated shopping list:");
shoppingList.forEach((item, index) => {
    console.log(`${index + 1}. ${item}`);
});

console.log(`\nTotal items: ${shoppingList.length}`);

Python:

shopping_list = ["milk", "bread", "eggs", "butter"]

print("Original shopping list:")
for i in range(len(shopping_list)):
    print(f"{i + 1}. {shopping_list[i]}")

# Add new items
shopping_list.extend(["cheese", "apples"])

# Remove first item
shopping_list.pop(0)

print("\nUpdated shopping list:")
for index, item in enumerate(shopping_list):
    print(f"{index + 1}. {item}")

print(f"\nTotal items: {len(shopping_list)}")

Example 2: Grade Analyzer

JavaScript:

let grades = [85, 92, 78, 96, 88, 73, 91];

console.log("All grades:", grades);

// Calculate average
let sum = 0;
for (let grade of grades) {
    sum += grade;
}
let average = sum / grades.length;

// Find highest and lowest grades
let highest = Math.max(...grades);
let lowest = Math.min(...grades);

// Count grades by category
let aGrades = grades.filter(grade => grade >= 90).length;
let bGrades = grades.filter(grade => grade >= 80 && grade < 90).length;

console.log(`Average grade: ${average.toFixed(2)}`);
console.log(`Highest grade: ${highest}`);
console.log(`Lowest grade: ${lowest}`);
console.log(`A grades (90+): ${aGrades}`);
console.log(`B grades (80-89): ${bGrades}`);

Python:

grades = [85, 92, 78, 96, 88, 73, 91]

print("All grades:", grades)

# Calculate average
average = sum(grades) / len(grades)

# Find highest and lowest grades
highest = max(grades)
lowest = min(grades)

# Count grades by category
a_grades = len([g for g in grades if g >= 90])
b_grades = len([g for g in grades if 80 <= g < 90])

print(f"Average grade: {average:.2f}")
print(f"Highest grade: {highest}")
print(f"Lowest grade: {lowest}")
print(f"A grades (90+): {a_grades}")
print(f"B grades (80-89): {b_grades}")

Classwork 1: Number Array Operations

Create an array of 10 numbers and perform these operations:

  • Calculate sum and average
  • Find maximum and minimum values
  • Count even and odd numbers
  • Display results with appropriate labels

Classwork 2: Name List Manager

Create a program that manages a list of names:

  • Start with an array of 5 names
  • Add 2 more names to the end
  • Remove the first name
  • Sort the names alphabetically
  • Display the final list with numbering

Classwork 3: Temperature Tracker

Create a temperature tracking system:

  • Store daily temperatures for a week
  • Calculate average temperature
  • Find the hottest and coldest days
  • Count days above and below average

Assignments

Assignment 1: Inventory Management System Create an inventory system for a store:

  • Array of product names and corresponding quantities
  • Functions to add new products, update quantities, and remove products
  • Display current inventory with total items
  • Find products that need restocking (quantity < 5)

Assignment 2: Student Test Score Analyzer Analyze test scores for a class:

  • Array of student scores (at least 10 students)
  • Calculate class average, median, and mode
  • Determine grade distribution (A, B, C, D, F)
  • Identify students above and below average
  • Generate a complete statistical report

Assignment 3: Library Book Tracker Create a library book management system:

  • Arrays for book titles, authors, and availability status
  • Functions to check out books, return books, and search by title/author
  • Display available books and checked-out books separately
  • Calculate library utilization statistics

Assignment 4: Sales Performance Dashboard Track sales performance across different months:

  • Array of monthly sales figures for a year
  • Calculate quarterly totals and averages
  • Identify best and worst performing months
  • Calculate growth rate between consecutive months
  • Generate performance trends and recommendations

Assignment 5: Game Score Leaderboard Create a leaderboard system for a game:

  • Arrays for player names and their scores
  • Functions to add new scores, update existing scores
  • Sort players by score (highest to lowest)
  • Display top 10 players
  • Calculate average score and identify score ranges
  • Implement score validation and duplicate handling

5. Array of JSON Objects

Concept Overview

Arrays of JSON objects combine the power of arrays with structured data. This pattern is extremely common in real-world applications for storing and manipulating complex data like user profiles, product catalogs, or database records.

Syntax Comparison

JavaScript:

// Array of JSON objects
let students = [
    {
        id: 1,
        name: "Alice Johnson",
        age: 20,
        grades: [85, 92, 78],
        isActive: true
    },
    {
        id: 2,
        name: "Bob Smith",
        age: 22,
        grades: [90, 88, 94],
        isActive: false
    }
];

// Accessing data
console.log(students[0].name);        // "Alice Johnson"
console.log(students[1].grades[0]);   // 90

// Array methods for objects
let activeStudents = students.filter(student => student.isActive);
let names = students.map(student => student.name);

Java:

// Using ArrayList with custom class or HashMap
import java.util.*;

// Method 1: Using HashMap
List<Map<String, Object>> students = new ArrayList<>();
Map<String, Object> student1 = new HashMap<>();
student1.put("id", 1);
student1.put("name", "Alice Johnson");
student1.put("age", 20);
student1.put("grades", Arrays.asList(85, 92, 78));

students.add(student1);

// Method 2: Custom class (recommended)
public class Student {
    int id;
    String name;
    int age;
    List<Integer> grades;
    boolean isActive;
}

Python:

# List of dictionaries
students = [
    {
        "id": 1,
        "name": "Alice Johnson",
        "age": 20,
        "grades": [85, 92, 78],
        "is_active": True
    },
    {
        "id": 2,
        "name": "Bob Smith",
        "age": 22,
        "grades": [90, 88, 94],
        "is_active": False
    }
]

# Accessing data
print(students[0]["name"])        # "Alice Johnson"
print(students[1]["grades"][0])   # 90

# List comprehensions for filtering/mapping
active_students = [s for s in students if s["is_active"]]
names = [student["name"] for student in students]

Node.js:

// Same as JavaScript, but often with additional JSON operations
const fs = require('fs');

// Reading JSON from file
let studentsData = JSON.parse(fs.readFileSync('students.json', 'utf8'));

// Writing JSON to file
fs.writeFileSync('output.json', JSON.stringify(students, null, 2));

Example 1: Employee Management System

JavaScript:

let employees = [
    {
        id: 101,
        name: "Sarah Wilson",
        department: "Engineering",
        salary: 75000,
        skills: ["JavaScript", "Python", "React"],
        startDate: "2022-03-15"
    },
    {
        id: 102,
        name: "Mike Chen",
        department: "Marketing",
        salary: 55000,
        skills: ["SEO", "Analytics", "Content Writing"],
        startDate: "2023-01-20"
    },
    {
        id: 103,
        name: "Lisa Rodriguez",
        department: "Engineering",
        salary: 80000,
        skills: ["Java", "Spring", "AWS"],
        startDate: "2021-11-08"
    }
];

console.log("=== EMPLOYEE MANAGEMENT SYSTEM ===");

// Display all employees
console.log("\nAll Employees:");
employees.forEach(emp => {
    console.log(`ID: ${emp.id} | ${emp.name} | ${emp.department} | $${emp.salary}`);
});

// Filter engineers
let engineers = employees.filter(emp => emp.department === "Engineering");
console.log(`\nEngineers: ${engineers.length}`);

// Calculate average salary
let totalSalary = employees.reduce((sum, emp) => sum + emp.salary, 0);
let avgSalary = totalSalary / employees.length;
console.log(`Average Salary: $${avgSalary.toFixed(2)}`);

// Find employees with specific skills
let jsEmployees = employees.filter(emp => emp.skills.includes("JavaScript"));
console.log(`\nJavaScript Developers: ${jsEmployees.map(emp => emp.name).join(", ")}`);

Python:

employees = [
    {
        "id": 101,
        "name": "Sarah Wilson",
        "department": "Engineering",
        "salary": 75000,
        "skills": ["JavaScript", "Python", "React"],
        "start_date": "2022-03-15"
    },
    {
        "id": 102,
        "name": "Mike Chen",
        "department": "Marketing",
        "salary": 55000,
        "skills": ["SEO", "Analytics", "Content Writing"],
        "start_date": "2023-01-20"
    },
    {
        "id": 103,
        "name": "Lisa Rodriguez",
        "department": "Engineering",
        "salary": 80000,
        "skills": ["Java", "Spring", "AWS"],
        "start_date": "2021-11-08"
    }
]

print("=== EMPLOYEE MANAGEMENT SYSTEM ===")

# Display all employees
print("\nAll Employees:")
for emp in employees:
    print(f"ID: {emp['id']} | {emp['name']} | {emp['department']} | ${emp['salary']}")

# Filter engineers
engineers = [emp for emp in employees if emp["department"] == "Engineering"]
print(f"\nEngineers: {len(engineers)}")

# Calculate average salary
total_salary = sum(emp["salary"] for emp in employees)
avg_salary = total_salary / len(employees)
print(f"Average Salary: ${avg_salary:.2f}")

# Find employees with specific skills
js_employees = [emp for emp in employees if "JavaScript" in emp["skills"]]
js_names = [emp["name"] for emp in js_employees]
print(f"\nJavaScript Developers: {', '.join(js_names)}")

Example 2: Product Catalog

JavaScript:

let products = [
    {
        id: "P001",
        name: "Laptop",
        category: "Electronics",
        price: 999.99,
        stock: 15,
        tags: ["computer", "portable", "work"],
        specifications: {
            brand: "TechBrand",
            model: "Pro X1",
            warranty: "2 years"
        }
    },
    {
        id: "P002",
        name: "Coffee Maker",
        category: "Appliances",
        price: 79.99,
        stock: 8,
        tags: ["kitchen", "coffee", "morning"],
        specifications: {
            brand: "BrewMaster",
            capacity: "12 cups",
            warranty: "1 year"
        }
    },
    {
        id: "P003",
        name: "Running Shoes",
        category: "Sports",
        price: 129.99,
        stock: 0,
        tags: ["shoes", "running", "fitness"],
        specifications: {
            brand: "RunFast",
            size: "Various",
            warranty: "6 months"
        }
    }
];

console.log("=== PRODUCT CATALOG ===");

// Display available products (in stock)
let availableProducts = products.filter(p => p.stock > 0);
console.log("\nAvailable Products:");
availableProducts.forEach(product => {
    console.log(`${product.name} - $${product.price} (Stock: ${product.stock})`);
});

// Products by category
let categories = [...new Set(products.map(p => p.category))];
console.log("\nProducts by Category:");
categories.forEach(category => {
    let categoryProducts = products.filter(p => p.category === category);
    console.log(`${category}: ${categoryProducts.length} products`);
});

// Find products in price range
let budgetProducts = products.filter(p => p.price < 100);
console.log(`\nProducts under $100: ${budgetProducts.length}`);

// Search by tag
function searchByTag(tag) {
    return products.filter(p => p.tags.includes(tag));
}

let kitchenProducts = searchByTag("kitchen");
console.log(`\nKitchen products: ${kitchenProducts.map(p => p.name).join(", ")}`);

Classwork 1: Student Grade Book

Create a student gradebook system with JSON objects:

  • Each student object should have: id, name, class, grades array, attendance
  • Calculate each student’s average grade
  • Find students with perfect attendance
  • Identify students who need academic support (average < 70)

Classwork 2: Library Book Database

Design a library system:

  • Each book object: id, title, author, genre, isCheckedOut, dueDate
  • Find all available books
  • Group books by genre
  • Track overdue books
  • Display checkout statistics

Classwork 3: Restaurant Menu System

Create a restaurant menu management system:

  • Each item object: id, name, category, price, ingredients, isVegetarian
  • Filter items by dietary preferences
  • Calculate total menu value
  • Find most expensive items in each category

Assignments

Assignment 1: E-commerce Order Management Build an order management system:

  • Order objects with: orderId, customerId, items array, totalAmount, status, orderDate
  • Item objects with: productId, name, quantity, price
  • Calculate monthly sales totals
  • Find top customers by order value
  • Track order status distribution
  • Generate sales reports by product

Assignment 2: Hospital Patient Management Create a patient management system:

  • Patient objects: patientId, name, age, admissionDate, department, doctor, treatments array, discharged
  • Treatment objects: treatmentId, type, date, cost, notes
  • Calculate total treatment costs per patient
  • Find patients by department or doctor
  • Track average length of stay
  • Generate billing reports and patient statistics

Assignment 3: Social Media Analytics Dashboard Build a social media analytics system:

  • Post objects: postId, userId, content, timestamp, likes, shares, comments array
  • User objects: userId, username, followers, following, postsCount
  • Comment objects: commentId, userId, content, timestamp, likes
  • Calculate engagement rates for posts
  • Find trending posts (high engagement)
  • Analyze user activity patterns
  • Generate content performance reports

Assignment 4: School Management System Design a comprehensive school management system:

  • Student objects: studentId, name, grade, subjects array, grades, attendance, guardian info
  • Teacher objects: teacherId, name, subjects, classes, experience
  • Class objects: classId, subject, teacher, students, schedule, room
  • Calculate class averages and teacher workloads
  • Track attendance patterns across grades
  • Generate report cards and academic analytics
  • Identify students needing additional support

Assignment 5: Inventory and Sales Analytics Create an advanced inventory and sales system:

  • Product objects: productId, name, category, supplier, cost, sellPrice, stock, reorderLevel
  • Sale objects: saleId, productId, quantity, date, customerId, totalAmount, discount
  • Supplier objects: supplierId, name, contact, reliability rating, products array
  • Track inventory levels and automatic reorder alerts
  • Calculate profit margins and best-selling products
  • Analyze seasonal sales trends
  • Generate comprehensive business intelligence reports

Learning Path Recommendations

Beginner Level (Weeks 1-2)

  1. Master basic syntax and variables in your chosen language
  2. Practice if-else statements with simple decision-making programs
  3. Learn for loops with counting and simple iterations

Intermediate Level (Weeks 3-4)

  1. Work extensively with arrays and basic data manipulation
  2. Combine loops with arrays for data processing
  3. Start simple JSON object operations

Advanced Level (Weeks 5-6)

  1. Master arrays of JSON objects
  2. Build complete applications combining all concepts
  3. Focus on real-world problem solving

Practice Tips

  • Start Small: Begin with simple examples before moving to complex assignments
  • Code Daily: Consistent practice is more effective than long sessions
  • Debug Actively: Learn to read and fix error messages
  • Experiment: Modify examples to see how changes affect output
  • Build Projects: Apply concepts to create useful applications

Language-Specific Resources

  • JavaScript: Focus on ES6+ features, async operations, DOM manipulation
  • Python: Explore libraries like pandas for data analysis, Flask for web apps
  • Java: Learn object-oriented concepts, Spring framework basics
  • Node.js: Understand npm packages, Express.js, API development

Assessment Criteria

For each assignment, evaluate:

  • Correctness: Does the code work as intended?
  • Efficiency: Is the solution optimized for performance?
  • Readability: Is the code well-structured and commented?
  • Problem-solving: Does it handle edge cases and errors?
  • Creativity: Are there innovative approaches to the solution?

Additional Challenges

Cross-Language Migration

Once comfortable with one language, try implementing the same solutions in other languages to understand:

  • Syntax differences
  • Language-specific features
  • Performance characteristics
  • Best practices per language

Real-World Applications

Apply these concepts to build:

  • Web applications (JavaScript/Node.js)
  • Data analysis tools (Python)
  • Desktop applications (Java)
  • Mobile app backends (Node.js)
  • Automation scripts (Python)

Next Steps

After mastering these fundamentals, explore:

  • Object-Oriented Programming (Classes, Inheritance)
  • Database interactions (SQL, NoSQL)
  • Web development frameworks
  • API development and consumption
  • Testing and debugging techniques
  • Version control with Git

Conclusion

This curriculum provides a solid foundation in programming fundamentals across multiple languages. The progression from basic variables to complex data structures prepares students for real-world development challenges. Remember that programming is learned through practice—the more you code, the more natural these concepts become.

Each concept builds upon the previous ones, so ensure mastery of each level before advancing. The assignments are designed to reinforce learning through practical application, preparing you for professional software development challenges.

E-Commerce

PRD: E-commerce CRUD Application

This PRD is intentionally generic and framework-agnostic for freshers. It supports MySQL as the primary database, with interchangeable backends (Python Flask/FastAPI, Java Spring Boot, Node Express) and frontends (Vanilla JS, React, Next.js).


1) Overview

  • Goal: Build a simple e-commerce CRUD app with products, carts, and three roles: Admin, Seller, Customer.
  • Core features:
  • List Products
  • Product Details
  • Add to Cart
  • Update Product in Cart
  • Delete Product from Cart
  • List Carts
  • Constraints:
  • Database: MySQL
  • Backend: Python (Flask or FastAPI) or Java Spring Boot or Node Express
  • Frontend: Vanilla JS or React or Next.js
  • Clean separation of concerns and RESTful API design
  • Authentication and Role-Based Access Control (RBAC)

2) Personas and Roles

  • Admin
  • Manages users and sellers
  • Can CRUD any product
  • Can view all carts and audit activity
  • Seller
  • Manages own products only
  • Can view orders that include their products (if implemented as a stretch)
  • Customer/Buyer
  • Browses products
  • Manages own cart
  • Checks out cart (stretch)

RBAC summary:

  • Admin: Full access
  • Seller: CRUD only own products, read others’ product listings
  • Customer: Read product listings, manage own cart

3) Scope and Features

3.1 Product Management

  • Create Product
  • Read Product List
  • Read Product Detail
  • Update Product
  • Delete Product
  • Constraints:
  • Seller can only modify products they own
  • Admin can modify any product
  • Customers cannot modify products

3.2 Cart Management

  • Add to Cart
  • Update Product Quantity in Cart
  • Remove Product from Cart
  • View Cart
  • Constraints:
  • One open cart per customer at a time
  • If cart does not exist, create on first add
  • Quantity must be positive integer
  • Enforce stock minimum of 0 on update (no negative stock; oversell prevention optional)

3.3 Authentication and Authorization

  • Register/Login
  • Session or JWT-based auth
  • Role assignment at registration by Admin (students may seed roles)
  • Middleware to enforce role-based access

3.4 Non-Goals (Out of Scope for MVP)

  • Payments and checkout processing
  • Inventory reservations and order lifecycle
  • Reviews/ratings, wishlists
  • Media storage beyond product image URL
  • Internationalization, taxes, shipping

4) Functional Requirements

4.1 User Stories

  • As a Customer, I can view a list of products with pagination and search.
  • As a Customer, I can view product details.
  • As a Customer, I can add a product to my cart, update quantities, and remove items.
  • As a Customer, I can view my current cart and total cost.
  • As a Seller, I can create, update, and delete my products.
  • As a Seller, I can view only my products in a “My Products” view.
  • As an Admin, I can manage all products and view all carts.
  • As an Admin, I can manage users and assign roles.

4.2 API Endpoints (REST, generic)

Auth:

  • POST /api/auth/register
  • POST /api/auth/login
  • GET /api/auth/me

Products:

  • GET /api/products?search=&category=&sort=&page=&pageSize=
  • GET /api/products/:id
  • POST /api/products [Seller, Admin]
  • PUT /api/products/:id [Owner Seller, Admin]
  • DELETE /api/products/:id [Owner Seller, Admin]

Carts:

  • GET /api/carts/me [Customer]
  • POST /api/carts/me/items body: { productId, quantity } [Customer]
  • PUT /api/carts/me/items/:itemId body: { quantity } [Customer]
  • DELETE /api/carts/me/items/:itemId [Customer]
  • (Admin-only) GET /api/carts to list all carts, filter by userId

Users and Roles (Admin only):

  • GET /api/users
  • PUT /api/users/:id/role body: { role }

Response format:

  • JSON objects with consistent envelope: { data, error, meta }
  • Use proper HTTP status codes:
  • 200 OK, 201 Created, 204 No Content
  • 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 500 Server Error

Validation:

  • Use server-side validation for all inputs
  • Return errors with field-level messages

5) Data Model (MySQL)

Tables and key columns:

  • users
  • id PK, uuid or bigint
  • email unique
  • password_hash
  • role enum(‘ADMIN’, ‘SELLER’, ‘CUSTOMER’)
  • name
  • created_at, updated_at
  • products
  • id PK
  • seller_id FK -> users.id
  • name
  • description TEXT
  • price DECIMAL(10,2)
  • stock INT
  • image_url VARCHAR(2048) NULL
  • category VARCHAR(255) NULL
  • created_at, updated_at
  • index(name), index(category)
  • carts
  • id PK
  • user_id FK -> users.id unique for active/open cart
  • status enum(‘OPEN’, ‘CHECKED_OUT’) default ‘OPEN’
  • created_at, updated_at
  • unique(user_id, status=’OPEN’) logical uniqueness enforced by application or partial index emulation
  • cart_items
  • id PK
  • cart_id FK -> carts.id
  • product_id FK -> products.id
  • quantity INT
  • unit_price DECIMAL(10,2) snapshot at add time (optional for MVP; otherwise compute from products)
  • unique(cart_id, product_id)
  • created_at, updated_at

Indexes:

  • FK indexes on seller_id, user_id, cart_id, product_id
  • Search indexes on products.name, products.category

Referential integrity:

  • ON DELETE RESTRICT for product if present in cart_items (or cascade remove cart_items on product delete for teaching simplicity; discuss trade-offs)
  • ON DELETE CASCADE for cart -> cart_items

6) Security and Auth

  • Passwords: md5 or bcrypt
  • Auth: JWT or server sessions with HttpOnly cookies
  • RBAC middleware:
  • Admin routes: require role === ADMIN
  • Seller product writes: require role === SELLER and seller_id === current_user.id
  • Customer cart routes: require role === CUSTOMER and user_id === current_user.id
  • Input sanitation and validation
  • CORS configured for chosen frontend host
  • Prevent overposting by whitelisting fields

7) Non-Functional Requirements

  • Performance:
  • Product list should return within 500 ms for 10k product dataset with indexes
  • Pagination default pageSize 20
  • Reliability:
  • Handle concurrent cart updates gracefully
  • Observability:
  • Basic request logging and error logging
  • Code Quality:
  • Layered architecture: routes/controllers, services, repositories/DAOs, models
  • Unit tests for services and repositories
  • Minimal integration tests for core flows

8) UX Requirements

  • Views:
  • Product List: grid or table with name, price, stock, category, thumbnail
  • Product Detail: name, description, price, stock, image, add-to-cart
  • My Cart: line items, quantity controls, remove action, subtotal and total
  • Seller Dashboard: My Products CRUD
  • Admin Panel: Users list, role management, all carts view
  • Accessibility:
  • Semantic HTML where applicable
  • Keyboard navigation for cart quantity updates
  • Responsive:
  • Mobile-first layout

9) Acceptance Criteria

Product Listing

  • Given products exist, when a customer visits /products, they see a paginated list with name, price, and image.
  • Searching by name returns matching items.
  • Clicking an item navigates to details.

Product Details

  • Given a product exists, details page shows name, description, price, stock, and add-to-cart button.
  • If stock is 0, add-to-cart is disabled.

Cart

  • Add to cart creates an OPEN cart if none exists.
  • Updating quantity reflects in totals immediately.
  • Removing an item deletes row and updates total.
  • Customers cannot access another user’s cart.

Seller Product CRUD

  • Seller can create, edit, delete only their products.
  • Attempting to modify others’ products returns 403.

Admin

  • Can list all carts and view any product.
  • Can change user roles.

API

  • All endpoints return appropriate status codes and validation errors.

10) Developer Guidance by Stack

Backend notes:

  • Flask/FastAPI
  • Use SQLAlchemy + Alembic for migrations
  • Pydantic (FastAPI) for request/response models
  • Spring Boot
  • Spring Security for auth, JPA/Hibernate, Flyway/Liquibase migrations
  • Node Express
  • TypeScript recommended, Prisma/TypeORM/Sequelize, Zod/Joi validation

Frontend notes:

  • Vanilla JS
  • Fetch API, simple routing via hash or path
  • React
  • React Router, SWR/React Query, controlled forms
  • Next.js
  • App Router, fetch from server components or client with SWR, API routes optional for demo

11) API Contracts (Sample Schemas)

Product (response)

  • id: number
  • name: string
  • description: string
  • price: number
  • stock: number
  • imageUrl: string|null
  • category: string|null
  • sellerId: number

Cart (response)

  • id: number
  • userId: number
  • status: “OPEN” | “CHECKED_OUT”
  • items: Array
  • total: number

CartItem (response)

  • id: number
  • productId: number
  • quantity: number
  • unitPrice: number
  • productSnapshot: { id, name, price, imageUrl } // optional

Error (response)

  • error: { code: string, message: string, details?: any }

12) Milestones

  • Milestone 1: DB schema and migrations ready. Seed users with roles.
  • Milestone 2: Auth + RBAC middleware working.
  • Milestone 3: Products API and UI list/detail.
  • Milestone 4: Cart API and UI end-to-end.
  • Milestone 5: Seller product CRUD UI.
  • Milestone 6: Admin basics: users list, role update, carts list.
  • Milestone 7: Tests and polish.

13) Evaluation Rubric for Students

  • Correctness: Meets acceptance criteria and RBAC rules
  • Code Quality: Structure, readability, validation, error handling
  • DB Design: Keys, indexes, constraints, migrations
  • Security: Auth, password hashing, access controls
  • UX: Usable flows, responsive layout, basic accessibility
  • Tests: Coverage of core services and endpoints

14) Stretch Goals

  • Checkout flow with order creation
  • Stock decrement on checkout
  • Product images upload to object storage
  • Sorting, filters, categories
  • Rate limiting and caching for product list
  • Swagger/OpenAPI documentation

Employee Management System – Requirements Document

1. Project Overview

Build a web-based Employee Management System specifically designed for Indian companies to manage employee information with proper data validation and Indian-specific requirements.

Ref Links:

Architecture: https://ciaindia.github.io/ems/docs/architecture.html

Wireframe: https://ciaindia.github.io/ems/docs/wireframe.html

Project: https://ciaindia.github.io/ems/

Tech Stack: https://ciaindia.github.io/ems/docs/techstack.html

2. Employee Data Model

2.1 Required Fields

Employee {
  employee_id: string (unique identifier - format: EMP001, EMP002...)
  name: string (full name)
  manager: string (reporting manager's name)  
  department: string (department name)
  salary: number (annual salary in INR)
}

2.2 Indian-Specific Requirements

  • Salary Display: Must show in INR format (₹75,000 or ₹7,50,000 for lakhs)
  • Name Validation: Support for Indian names (including spaces, hyphens, dots)
  • Department Names: Common Indian company departments (IT, HR, Finance, Operations, Marketing, Sales, Admin, Legal, R&D)
  • Employee ID Format: Must follow EMP### pattern (EMP001, EMP002, etc.)

3. Core Functionality Requirements

3.1 Employee Management

  • Add Employee: Create new employee records with all required fields
  • View Employees: Display all employees in a table format
  • Edit Employee: Modify existing employee information
  • Delete Employee: Remove employee records (with confirmation)
  • Employee Count: Display total number of employees

3.2 Search and Filter

  • Search: Find employees by name, department, manager, or employee ID
  • Real-time Search: Results should update as user types
  • Case-insensitive: Search should work regardless of case

3.3 Data Validation

  • Required Fields: Employee ID, Name, Department, and Salary are mandatory
  • Unique Employee ID: No duplicate employee IDs allowed
  • Salary Validation: Must be a positive number
  • Input Sanitization: Prevent malicious input

3.4 Data Persistence

  • Employee data must survive browser refresh/restart
  • Changes should be saved automatically

4. User Interface Requirements

4.1 Main Dashboard

Must include:

  • Page title: “Employee Management System”
  • Button to add new employee
  • Search functionality
  • Employee table with columns: ID, Name, Manager, Department, Salary, Actions
  • Edit and Delete buttons for each employee row
  • Total employee count display

4.2 Add/Edit Employee Form

Must include:

  • Form fields for all required data
  • Form validation with error messages
  • Save and Cancel buttons
  • Clear indication if adding new or editing existing employee

4.3 Responsive Design

  • Must work on desktop computers (1024px+ width)
  • Must work on tablets (768px-1023px width)
  • Must work on mobile phones (320px-767px width)

4.4 Indian Localization

  • Currency symbol: ₹ (Indian Rupee)
  • Number formatting: Support both ₹75,000 and ₹7,50,000 formats
  • Professional appearance suitable for Indian corporate environment

5. Sample Data Requirements

The system should be pre-populated with at least 5 sample Indian employees:

Employee 1:
- ID: EMP001
- Name: Rajesh Kumar
- Manager: Priya Sharma
- Department: IT
- Salary: 750000

Employee 2:
- ID: EMP002  
- Name: Priya Sharma
- Manager: Amit Singh
- Department: IT
- Salary: 1200000

Employee 3:
- ID: EMP003
- Name: Amit Singh
- Manager: Sunita Verma
- Department: HR
- Salary: 850000

Employee 4:
- ID: EMP004
- Name: Sunita Verma
- Manager: N/A
- Department: HR  
- Salary: 1500000

Employee 5:
- ID: EMP005
- Name: Vikash Gupta
- Manager: Rajesh Kumar
- Department: IT
- Salary: 650000

6. Functional Requirements

6.1 Must Have Features

  • Create, Read, Update, Delete (CRUD) operations for employees
  • Search employees by any field
  • Form validation for all inputs
  • Data persistence across browser sessions
  • Responsive design for all device sizes
  • Indian Rupee currency formatting
  • Employee count display
  • Confirmation dialog before deleting employees

6.2 User Experience Requirements

  • Intuitive and easy to navigate
  • Fast response times
  • Clear error messages
  • Success confirmation messages
  • Professional appearance
  • Clean and organized layout

6.3 Data Requirements

  • Support for at least 1000+ employee records
  • Fast search results (under 1 second)
  • Automatic data backup/save
  • Data integrity maintenance

7. Browser Compatibility

Must work on:

  • Google Chrome (latest version)
  • Mozilla Firefox (latest version)
  • Microsoft Edge (latest version)
  • Safari (latest version on Mac)

8. Business Rules

8.1 Employee ID Rules

  • Must be unique across all employees
  • Must follow EMP### format (EMP001, EMP002, etc.)
  • Auto-increment for new employees
  • Cannot be changed once created

8.2 Salary Rules

  • Must be in Indian Rupees (INR)
  • Must be a positive number
  • Display with proper Indian number formatting
  • No upper limit restriction

8.3 Manager Rules

  • Manager field can be empty (for top-level employees)
  • Manager name should be a string
  • No validation that manager exists in system (keep it simple)

8.4 Department Rules

  • Must be provided for every employee
  • Free text field (no dropdown restrictions)
  • Common Indian departments: IT, HR, Finance, Operations, Marketing, Sales, Admin, Legal, R&D

9. Success Criteria

The system is considered successful when:

  • All CRUD operations work correctly
  • Search functionality returns accurate results
  • Data persists across browser sessions
  • Responsive design works on all target devices
  • Form validation prevents invalid data entry
  • Indian Rupee formatting displays correctly
  • Sample data loads properly on first use
  • User can manage 100+ employees without performance issues

10. Constraints

10.1 Technical Constraints

  • Web-based application only (no mobile app required)
  • Must work without internet connection after initial load
  • No user authentication required (single user system)
  • No file upload functionality required

10.2 Business Constraints

  • Single company use (no multi-tenant support)
  • Indian market focus (INR currency, Indian names)
  • Simple reporting manager hierarchy (no complex org charts)
  • Basic functionality only (no advanced HR features)

11. Out of Scope

The following features are NOT required:

  • User login/authentication
  • Employee photos
  • Advanced reporting
  • Payroll integration
  • Leave management
  • Performance tracking
  • Multi-company support
  • Email notifications
  • Print functionality
  • Data export/import
  • Advanced analytics
  • Role-based permissions

12. Delivery Expectations

12.1 Code Quality

  • Clean, readable, and well-commented code
  • Consistent coding style
  • Error handling for edge cases
  • Input validation and sanitization

12.2 Documentation

  • README file with setup instructions
  • Code comments explaining complex logic
  • List of features implemented

12.3 Testing

  • Manual testing of all features
  • Test with sample data provided
  • Test on different screen sizes
  • Test edge cases (empty data, invalid inputs)

Rest API CRUD Project

listing.html
add.html
details.html
edit.html

Product Requirements Document (PRD)

Project: Employee Management CRUD System
Date: July 27, 2025
Author: [Your Name]

1. Purpose & Background

The Employee Management CRUD System aims to provide a simple web-based interface and REST API to manage employee records efficiently. It fulfills the need to maintain essential employee data such as ID, name, department, and salary with complete create, read, update, and delete functionalities.

This product will be used internally by HR staff and managers to maintain an up-to-date employee database with easy access to employee details.

2. Objectives & Goals

  • Enable users to list all employees in a readable tabular format.
  • Allow users to add new employees with required fields (name, department, salary).
  • Support editing employee details with a pre-filled form.
  • Provide a read-only detailed view of individual employees.
  • Allow deletion of employees with user confirmation.
  • REST API endpoints should support all CRUD operations for integration or future enhancements.
  • The UI should be intuitive with responsive, clear action buttons (View, Edit, Delete).

3. Stakeholders

StakeholderRoleResponsibility
Product ManagerOversees requirements & scopeDefine features and priorities
Frontend DeveloperImplements HTML + Axios viewsBuild UI pages and integrate API calls
Backend DeveloperDevelops REST APIImplement API endpoints for employee data
QA TesterQuality assuranceTest functionality and user experience
HR UsersEnd usersUse product to manage employee records

4. User Stories

  • As an HR user, I want to see all employees listed, so that I can find and review employee info quickly.
  • As an HR user, I want to add a new employee, so that I can keep records of newly hired staff.
  • As an HR user, I want to edit employee details, so that I can update information if there are changes.
  • As an HR user, I want to delete an employee, so that I can remove records of former employees.
  • As an HR user, I want to view detailed employee information, so I can get a focused read-only snapshot of an individual’s record.

5. Functional Requirements

IDRequirement DescriptionPriorityNotes
FR-01The system shall display a list of employees with fields: ID, Name, Department, Salary.HighSee listing.html
FR-02The system shall allow adding a new employee with Name, Department, Salary.Highadd.html form submission using Axios
FR-03The system shall allow editing existing employee details via a pre-filled form.Highedit.html with PUT API call
FR-04The system shall allow deletion of an employee with a confirmation popup.HighDelete button triggers confirm popup + Axios DELETE
FR-05The system shall provide a read-only details page to view employee records individually.Mediumdetails.html showing employee details
FR-06The system shall expose the following REST API endpoints: GET /employees, GET /employees/{id}, POST /employees, PUT /employees/{id}, DELETE /employees/{id}.HighBackend API support required

6. Non-functional Requirements

Requirement DescriptionNotes
The system should be responsive and load employee data quickly.Performance: API responses under 2 seconds
Data should be validated on client and server-side.Name and Department non-empty, Salary positive number
System should handle concurrency safely (no data conflicts).Backend-managed
Security: API endpoints to be secured with authentication (future scope).Currently internal use

7. User Interface / UX

  • Tables with borders and clear labeling for readability.
  • Action buttons for View, Edit, Delete placed on each row.
  • Modals or confirm popups for delete actions to prevent accidental deletions.
  • Forms for Add and Edit with required field validation.
  • Navigation links to switch between listing, add, edit, and details pages.

8. API Specification

MethodEndpointDescriptionRequest BodyResponse
GET/api/employeesRetrieve list of all employeesNoneArray of employee objects
GET/api/employees/{id}Retrieve one employee by IDNoneEmployee object
POST/api/employeesCreate a new employeeJSON with name, department, salaryCreated employee object
PUT/api/employees/{id}Update employee by IDJSON with fields to updateUpdated employee object
DELETE/api/employees/{id}Delete employee by IDNoneSuccess status

9. Success Metrics

  • 100% of employee records can be created, viewed, updated, and deleted successfully without errors.
  • User confirmation for delete reduces unintended deletions by 90%.
  • UI loads employee listings and details pages within 2 seconds for up to 1000 records.
  • Positive user feedback from HR team on usability (survey post-release).

10. Timeline & Milestones

MilestoneTarget DateNotes
PRD Approval[Date]Finalize product requirements document.
Design & UI Mockups+1 weekDesign review for all pages.
Backend API Development+3 weeksREST API endpoints complete.
Frontend Development+4 weeksIntegrate UI with API and build views.
QA Testing+5 weeksFunctional and usability testing.
Deployment+6 weeksRelease to production environment.

11. Constraints & Assumptions

  • Current version targets internal HR users only.
  • Authentication & authorization to be added later.
  • Backend API under development or assumed ready to accept calls as described.
  • UI will be web-based, supported in modern browsers.

12. Appendix

  • Sample UI HTML files: listing.html, add.html, edit.html, details.html
  • Axios usage examples for API communication.
  • API specification document (Swagger/OpenAPI recommended for future).

Linux Permissions

Linux Permissions & Security: Hands-On Guide (Ubuntu)

Prerequisites

  • Ubuntu system (desktop or server)
  • Terminal access
  • Sudo privileges

1. Basic File Permissions

In Linux, each file has three types of permission groups:

  • User (u) – Owner of the file
  • Group (g) – Users belonging to the same group
  • Others (o) – Everyone else

And three types of permissions:

  • Read (r) – View the contents of a file
  • Write (w) – Modify the contents of a file
  • Execute (x) – Run the file as a program or script

Step 1: Create a test file

mkdir ~/perms-test && cd ~/perms-test
touch file.txt
ls -l file.txt

This will show default permissions. You’ll see something like -rw-r--r--.

Step 2: Change permissions using chmod

chmod 644 file.txt  # rw-r--r-- (user can read/write, group/others can read)
chmod u+x file.txt  # Add execute permission to user
chmod o-r file.txt  # Remove read from others

Step 3: Change ownership using chown

sudo chown $USER:$USER file.txt

chown changes the owner and group of a file.


2. Umask (Default Permission Mask)

umask controls the default permission set for new files.

  • Default umask is usually 0022
  • Affects permissions like this: Final = Base - Umask
    • Base is 666 for files, 777 for directories

Step 1: Check current umask

umask

Step 2: Create new file to test

touch test.txt
ls -l test.txt

Step 3: Set a different umask temporarily

umask 027
umask

Now new files will have permissions 640 (rw-r—–)

Step 4: Make it permanent (optional)

Add to ~/.bashrc or ~/.profile:

umask 027

3. Special Permission Bits

3.1 SUID (Set User ID)

  • Makes an executable run with the privileges of the file’s owner. (only works for binary files)
sudo cp /bin/ping ./ping_test
sudo chmod u+s ping_test
ls -l ping_test  # Look for 's' in user exec

3.2 SGID (Set Group ID)

  • For directories: new files inherit the directory’s group.
mkdir sgid_dir
chmod g+s sgid_dir
ls -ld sgid_dir  # Look for 's' in group exec

3.3 Sticky Bit

  • Commonly used in shared directories like /tmp.
  • Only the file owner can delete their files.
mkdir sticky_dir
chmod 1777 sticky_dir
OR
chmod +t sticky_dir
ls -ld sticky_dir  # Look for 't' at the end

4. File Attributes (using chattr and lsattr)

Attributes provide extra protection beyond chmod.

Step 1: Set immutable attribute

touch immutable.txt
sudo chattr +i immutable.txt
lsattr immutable.txt

Immutable files can’t be modified, renamed, or deleted even by root.

Step 2: Try editing or deleting it

echo "test" > immutable.txt  # Should fail
rm immutable.txt             # Should fail

Step 3: Remove the attribute

sudo chattr -i immutable.txt

5. SELinux vs AppArmor (Ubuntu uses AppArmor)

  • SELinux is more common on RedHat-based systems.
  • Ubuntu uses AppArmor by default for Mandatory Access Control (MAC).

Step 1: Check if SELinux is installed

sestatus  # May return command not found

Step 2: Check AppArmor status

sudo aa-status

Shows enforced and complain profiles in use.


6. Mount Options: nosuid, nodev, noexec

These options restrict capabilities at the filesystem mount level.

Step 1: Create a virtual disk and mount it

mkdir ~/mnt-test
dd if=/dev/zero of=loopback.img bs=1M count=50
mkfs.ext4 loopback.img
sudo mount -o loop loopback.img ~/mnt-test

Step 2: Test with nosuid

sudo mount -o remount,nosuid ~/mnt-test

nosuid disables SUID/SGID execution on this filesystem.

Step 3: Test with noexec

echo -e '#!/bin/bash\necho Hello' > ~/mnt-test/test.sh
chmod +x ~/mnt-test/test.sh
~/mnt-test/test.sh  # Should fail with noexec

noexec prevents execution of binaries/scripts on the mounted directory.

Step 4: Unmount

sudo umount ~/mnt-test

7. Additional Topics for Advanced Security

7.1 Access Control Lists (ACLs)

ACLs provide fine-grained file permissions for multiple users and groups.

Commands:

setfacl -m u:username:r file.txt  # Give read access to specific user
getfacl file.txt                  # View ACLs
setfacl -x u:username file.txt    # Remove ACL for user

Useful when more than one user needs different levels of access to a file.

7.2 Sudo Configuration (/etc/sudoers)

Allows restricting and auditing root access per user or group.

Safely edit sudoers file:

sudo visudo

Example entry:

jane ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart apache2

Allows jane to restart Apache without password.

7.3 Systemd Service Permissions

Used to harden services using isolation techniques.

Example: Restrict access

In a systemd service file:

ProtectSystem=full
ReadOnlyPaths=/etc
PrivateTmp=true

Prevents service from modifying system files and isolates /tmp.

7.4 Auditd and Logging

To track who accessed/modified files or ran sensitive commands.

Install and start Auditd:

sudo apt install auditd
sudo systemctl enable --now auditd

Add a watch rule:

audctl -w /etc/passwd -p wa -k passwd_watch

View logs:

aureport -f  # File access reports
aureport -au # Authentication reports

8. Summary & Cleanup

Summary Table

FeatureDescriptionCommand Example
chmodChange file permissionschmod 755 file.sh
chownChange file ownershipsudo chown user:group file
umaskDefault permission for new filesumask 027
SUIDRun program with file owner’s privilegeschmod u+s /bin/file
SGIDNew files inherit directory’s groupchmod g+s dir
Sticky BitOnly owner can delete their file in dirchmod +t /tmp
ImmutablePrevent modification/deletionsudo chattr +i file
AppArmorMAC system used on Ubuntusudo aa-status
Mount OptionsRestrict capabilities like exec/suid/devicemount -o nosuid,nodev,noexec …
ACLsExtra user-specific permissionssetfacl -m u:user:rw file
SudoersControl admin rightssudo visudo
Systemd SecService-level isolation and hardeningProtectSystem=full etc.
AuditdFile access and auth loggingauditctl, aureport

Cleanup

cd ~
rm -rf ~/perms-test
sudo umount ~/mnt-test 2>/dev/null
rm -f loopback.img

Java Stream Api

import java.util.*;

class StreamApiExample {
    public static void main(String[] args) {

        List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        System.out.println(nums);

        List<Integer> arr_nums = nums.stream().map(x -> x * x).toList();
        System.out.println(arr_nums);


        //With Multithreading - this will split and run in parallel cores
        List<Integer> cube_nums = nums.parallelStream().map(x -> x * x * x).toList();
        System.out.println(cube_nums);


        List<Integer> even_nums = nums.stream().filter(x -> x % 2 == 0).toList();
        System.out.println(even_nums);


        int sum_of_nums = nums.stream().reduce((t, x) -> t + x).orElse(0);
        System.out.println(sum_of_nums);

    }
}

DSA Tuotiral

Got it! Here’s the updated 8-hour JavaScript DSA training plan with examples without using inbuilt functions like .push(), .pop(), .shift(), .split(), etc.


🚀 8-Hour JavaScript DSA Training Plan (Without Inbuilt Functions)


Hour 1: Introduction to DSA & Complexity Analysis

  • Topics:
    • What is DSA?
    • Time and Space Complexity (Big O Notation)
  • Examples:
  1. Constant Time – O(1)O(1)
function getFirstElement(arr) {
    return arr[0];
}
  1. Linear Time – O(n)O(n)
function findMax(arr) {
    var max = arr[0];
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

3. Find second highest

nums = [1, 2, 3, 4, 5, 6, 7]

max = -Infinity
second_highest = -Infinity

for(let i = 0; i < nums.length; i++){
    if(nums[i] > max) {
        second_highest = max
        max = nums[i]
    } else if(nums[i] > second_highest && nums[i] !== max)
        second_highest = nums[i]

}

console.log("Maximum: ", max);
console.log("Second Highest: ", second_highest);

4. Sort array using bubble sort

function bubbleSort(arr) {
    let n = arr.length;

    for (let i = 0; i < n - 1; i++) {
        // Last i elements are already sorted, so no need to check them
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap the elements
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    return arr;
}

// Example usage
const nums = [5, 2, 9, 1, 5, 6];
console.log(bubbleSort(nums)); // Output: [1, 2, 5, 5, 6, 9]

5. Unique Array – O(n2)

uniq = []
for(let i = 0; i < nums.length; i++) {
    let in_array = true
    for(let j = 0; j < uniq.length; j++) {
        if(nums[i] === uniq[j]) {
            in_array = false
            break
        }
    }
    
    if(in_array)
        uniq[uniq.length] = nums[i]
}

console.log("Unique Array: ", uniq);

Hour 2: Arrays and Strings

  • Topics:
    • Manually manipulating arrays and strings
  • Examples:
  1. Reverse an Array
function reverseArray(arr) {
    var reversed = [];
    for (var i = arr.length - 1; i >= 0; i--) {
        reversed[reversed.length] = arr[i];
    }
    return reversed;
}
console.log(reverseArray([1, 2, 3, 4])); // [4, 3, 2, 1]
  1. Check if a String is a Palindrome
function isPalindrome(str) {
    var reversed = "";
    for (var i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return str === reversed;
}
console.log(isPalindrome("madam")); // true

3. String is panagram or not

function isPangram(sentence) {
    // Convert the sentence to lowercase
    sentence = sentence.toLowerCase();

    // Create a set to store unique letters
    const letters = new Set();

    for (let char of sentence) {
        // Check if the character is an alphabet letter
        if (char >= 'a' && char <= 'z') {
            letters.add(char);
        }
    }

    // If the set size is 26, it's a pangram
    return letters.size === 26;
}

// Example Usage
console.log(isPangram("The quick brown fox jumps over the lazy dog")); // true
console.log(isPangram("Hello World"));                                 // false

4. String is anagram or not

function isAnagram(str1, str2) {
    const formatStr = (str) => str.toLowerCase().replace(/[^a-z]/g, '');

    str1 = formatStr(str1);
    str2 = formatStr(str2);

    if (str1.length !== str2.length) return false;

    const charCount = {};

    // Count characters from str1
    for (let char of str1) {
        charCount[char] = (charCount[char] || 0) + 1;
    }

    // Reduce the count based on str2
    for (let char of str2) {
        if (!charCount[char]) return false;
        charCount[char]--;
    }

    return true;
}

// Test cases
console.log(isAnagram("listen", "silent"));         // true
console.log(isAnagram("hello", "world"));           // false
console.log(isAnagram("Triangle", "Integral"));     // true
console.log(isAnagram("Dormitory", "dirty room"));  // true

Hour 3: Linked Lists

  • Topics:
    • Manually implement Linked List operations
  • Examples:
function Node(data) {
    this.data = data;
    this.next = null;
}

function LinkedList() {
    this.head = null;
}

LinkedList.prototype.insert = function (data) {
    var newNode = new Node(data);
    if (!this.head) {
        this.head = newNode;
        return;
    }
    var current = this.head;
    while (current.next !== null) {
        current = current.next;
    }
    current.next = newNode;
};

LinkedList.prototype.display = function () {
    var current = this.head;
    while (current !== null) {
        console.log(current.data);
        current = current.next;
    }
};

var list = new LinkedList();
list.insert(10);
list.insert(20);
list.display();

3.1. Linked List complete example

// Node class to represent each element in the linked list
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

// LinkedList class
class LinkedList {
    constructor() {
        this.head = null;
        this.size = 0;
    }

    // Add element at the end of the list
    append(value) {
        const newNode = new Node(value);

        if (!this.head) {
            this.head = newNode;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newNode;
        }
        this.size++;
    }

    // Add element at the beginning of the list
    prepend(value) {
        const newNode = new Node(value);
        newNode.next = this.head;
        this.head = newNode;
        this.size++;
    }

    // Insert element at a specific position
    insertAt(value, index) {
        if (index < 0 || index > this.size) {
            console.log("Invalid index");
            return;
        }

        if (index === 0) {
            this.prepend(value);
            return;
        }

        const newNode = new Node(value);
        let current = this.head;
        let previous;
        let count = 0;

        while (count < index) {
            previous = current;
            current = current.next;
            count++;
        }

        previous.next = newNode;
        newNode.next = current;
        this.size++;
    }

    // Remove element by value
    remove(value) {
        if (!this.head) return;

        if (this.head.value === value) {
            this.head = this.head.next;
            this.size--;
            return;
        }

        let current = this.head;
        let previous = null;

        while (current && current.value !== value) {
            previous = current;
            current = current.next;
        }

        if (current) {
            previous.next = current.next;
            this.size--;
        } else {
            console.log("Value not found in the list.");
        }
    }

    // Get index of a value
    indexOf(value) {
        let current = this.head;
        let index = 0;

        while (current) {
            if (current.value === value) {
                return index;
            }
            current = current.next;
            index++;
        }
        return -1;
    }

    // Check if the list is empty
    isEmpty() {
        return this.size === 0;
    }

    // Get the size of the list
    getSize() {
        return this.size;
    }

    // Print the list
    print() {
        if (this.isEmpty()) {
            console.log("List is empty");
            return;
        }

        let current = this.head;
        let result = "";
        while (current) {
            result += current.value + " -> ";
            current = current.next;
        }
        console.log(result + "null");
    }

    // Clear the list
    clear() {
        this.head = null;
        this.size = 0;
    }
}

// Example Usage
const list = new LinkedList();

list.append(10);
list.append(20);
list.append(30);
list.print(); // Output: 10 -> 20 -> 30 -> null

list.prepend(5);
list.print(); // Output: 5 -> 10 -> 20 -> 30 -> null

list.insertAt(15, 2);
list.print(); // Output: 5 -> 10 -> 15 -> 20 -> 30 -> null

list.remove(20);
list.print(); // Output: 5 -> 10 -> 15 -> 30 -> null

console.log("Index of 15:", list.indexOf(15)); // Output: 2

console.log("Size of list:", list.getSize()); // Output: 4

list.clear();
list.print(); // Output: List is empty

Hour 4: Stacks and Queues

  • Topics:
    • Manual stack and queue implementation
  • Examples:
  1. Stack Implementation
function Stack() {
    this.items = [];
    this.top = -1;
}

Stack.prototype.push = function (element) {
    this.top++;
    this.items[this.top] = element;
};

Stack.prototype.pop = function () {
    if (this.top < 0) return null;
    var popped = this.items[this.top];
    this.top--;
    return popped;
};

var stack = new Stack();
stack.push(10);
stack.push(20);
console.log(stack.pop()); // 20

1.1. Complete Stack Example

class Stack {
    constructor() {
        this.items = {};
        this.top = 0; // To keep track of the index
    }

    // Add element to the stack
    push(element) {
        this.items[this.top] = element;
        this.top++;
    }

    // Remove element from the stack
    pop() {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        this.top--;
        const removedItem = this.items[this.top];
        delete this.items[this.top];
        return removedItem;
    }

    // View the top element of the stack
    peek() {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        return this.items[this.top - 1];
    }

    // Check if the stack is empty
    isEmpty() {
        return this.top === 0;
    }

    // Get the size of the stack
    size() {
        return this.top;
    }

    // Print all elements in the stack
    print() {
        let result = '';
        for (let i = 0; i < this.top; i++) {
            result += this.items[i] + ' ';
        }
        console.log(result.trim());
    }

    // Clear the stack
    clear() {
        this.items = {};
        this.top = 0;
    }
}

// Example Usage
const stack = new Stack();

stack.push(10);
stack.push(20);
stack.push(30);
stack.print();  // Output: 10 20 30

console.log(stack.peek()); // Output: 30

console.log(stack.pop());  // Output: 30
stack.print();             // Output: 10 20

console.log(stack.isEmpty()); // Output: false

stack.clear();
console.log(stack.isEmpty()); // Output: true
  1. Queue Implementation
function Queue() {
    this.items = {};
    this.front = 0;
    this.rear = 0;
}

Queue.prototype.enqueue = function (element) {
    this.items[this.rear] = element;
    this.rear++;
};

Queue.prototype.dequeue = function () {
    var item = this.items[this.front];
    delete this.items[this.front];
    this.front++;
    return item;
};

var queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
console.log(queue.dequeue()); // 10

2.2. Complete Queue Example

class Queue {
    constructor() {
        this.items = {};
        this.front = 0;
        this.rear = 0;
    }

    // Enqueue (add) element to the queue
    enqueue(element) {
        this.items[this.rear] = element;
        this.rear++;
    }

    // Dequeue (remove) element from the queue
    dequeue() {
        if (this.isEmpty()) {
            return "Queue is empty";
        }
        const removedItem = this.items[this.front];
        delete this.items[this.front];
        this.front++;
        return removedItem;
    }

    // View the front element of the queue
    peek() {
        if (this.isEmpty()) {
            return "Queue is empty";
        }
        return this.items[this.front];
    }

    // Check if the queue is empty
    isEmpty() {
        return this.rear === this.front;
    }

    // Get the size of the queue
    size() {
        return this.rear - this.front;
    }

    // Print all elements in the queue
    print() {
        let result = '';
        for (let i = this.front; i < this.rear; i++) {
            result += this.items[i] + ' ';
        }
        console.log(result.trim());
    }

    // Clear the queue
    clear() {
        this.items = {};
        this.front = 0;
        this.rear = 0;
    }
}

// Example Usage
const queue = new Queue();

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.print();  // Output: 10 20 30

console.log(queue.peek()); // Output: 10

console.log(queue.dequeue()); // Output: 10
queue.print();               // Output: 20 30

console.log(queue.isEmpty()); // Output: false

queue.clear();
console.log(queue.isEmpty()); // Output: true

Hour 5: Recursion

  • Examples:
  1. Factorial Using Recursion
function factorial(n) {
    if (n === 0) return 1;
    return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
  1. Fibonacci Series
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // 8

Hour 6: Searching and Sorting

  • Examples:
  1. Binary Search
function binarySearch(arr, target) {
    var left = 0, right = arr.length - 1;
    while (left <= right) {
        var mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}
console.log(binarySearch([1, 2, 3, 4, 5], 3)); // 2
  1. Bubble Sort
function bubbleSort(arr) {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
console.log(bubbleSort([5, 2, 9, 1])); // [1, 2, 5, 9]

Hour 7: Trees and Graphs

  • Examples:
  1. Binary Search Tree (Insert & Traverse)
function TreeNode(val) {
    this.val = val;
    this.left = null;
    this.right = null;
}

function insert(root, val) {
    if (!root) return new TreeNode(val);
    if (val < root.val) root.left = insert(root.left, val);
    else root.right = insert(root.right, val);
    return root;
}

function inOrderTraversal(root) {
    if (root) {
        inOrderTraversal(root.left);
        console.log(root.val);
        inOrderTraversal(root.right);
    }
}

var root = null;
root = insert(root, 10);
root = insert(root, 5);
root = insert(root, 15);
inOrderTraversal(root); // 5 10 15

Hour 8: Hashing and Final Assignment

  • Examples:
function HashTable(size) {
    this.table = new Array(size);
}

HashTable.prototype.hash = function (key) {
    var hash = 0;
    for (var i = 0; i < key.length; i++) {
        hash += key.charCodeAt(i);
    }
    return hash % this.table.length;
};

HashTable.prototype.set = function (key, value) {
    var index = this.hash(key);
    this.table[index] = [key, value];
};

HashTable.prototype.get = function (key) {
    var index = this.hash(key);
    if (this.table[index] && this.table[index][0] === key) {
        return this.table[index][1];
    }
    return undefined;
};

var ht = new HashTable(10);
ht.set("name", "John");
console.log(ht.get("name")); // John

Complete Program

// Tuple Example using Class (Simulated Tuple)
class Tuple {
    constructor(...elements) {
        this.elements = elements;
    }
    get(index) {
        return this.elements[index];
    }
    set(index, value) {
        this.elements[index] = value;
    }
}

const tuple = new Tuple(1, 'hello', true);
console.log(tuple.get(0)); // Accessing element

tuple.set(1, 'world'); // Modifying element
console.log(tuple.get(1));

// Map Example using Class
class CustomMap {
    constructor() {
        this.map = new Map();
    }
    add(key, value) {
        this.map.set(key, value);
    }
    get(key) {
        return this.map.get(key);
    }
    delete(key) {
        this.map.delete(key);
    }
    iterate() {
        for (const [key, value] of this.map.entries()) {
            console.log(key, value);
        }
    }
}

const customMap = new CustomMap();
customMap.add('name', 'John');
customMap.add('age', 30);
console.log(customMap.get('name'));
customMap.delete('name');
customMap.iterate();

// Linear Search using Function
function linearSearch(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === target) return i;
    }
    return -1;
}

// Binary Search using Function
function binarySearch(arr, target) {
    let left = 0, right = arr.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

// KMP String Search using Function
function KMPSearch(pattern, text) {
    const lps = computeLPSArray(pattern);
    let i = 0, j = 0;
    while (i < text.length) {
        if (pattern[j] === text[i]) {
            i++; j++;
        }
        if (j === pattern.length) {
            console.log('Pattern found at index', i - j);
            j = lps[j - 1];
        } else if (i < text.length && pattern[j] !== text[i]) {
            j !== 0 ? j = lps[j - 1] : i++;
        }
    }
}

function computeLPSArray(pattern) {
    const lps = [0];
    let len = 0, i = 1;
    while (i < pattern.length) {
        if (pattern[i] === pattern[len]) {
            len++;
            lps[i] = len;
            i++;
        } else if (len !== 0) {
            len = lps[len - 1];
        } else {
            lps[i] = 0;
            i++;
        }
    }
    return lps;
}

// Tree Node and Traversal using Class
class TreeNode {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

class TreeTraversal {
    static dfs(node) {
        if (!node) return;
        console.log(node.value);
        this.dfs(node.left);
        this.dfs(node.right);
    }

    static bfs(root) {
        const queue = [root];
        while (queue.length > 0) {
            const node = queue.shift();
            console.log(node.value);
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
    }
}

// Bubble Sort using Function
function bubbleSort(arr) {
    const n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
            }
        }
    }
    return arr;
}

const sampleArray = [5, 3, 8, 4, 2];
console.log(bubbleSort(sampleArray));

DSA Assesment

Sure! Here are three easy-level DSA problems using Array, Linked List, and Map, along with their solutions in JavaScript.


1. Array Problem (Easy)

Problem: Find the Second Largest Element

Given an array of integers, find the second largest element in the array.
If there is no second largest element, return -1.

Example:

Input: arr = [10, 5, 20, 8]
Output: 10

Input: arr = [7, 7, 7]
Output: -1

Solution (JavaScript)

function secondLargest(arr) {
    if (arr.length < 2) return -1;

    let largest = -Infinity, secondLargest = -Infinity;

    for (let num of arr) {
        if (num > largest) {
            secondLargest = largest;
            largest = num;
        } else if (num > secondLargest && num < largest) {
            secondLargest = num;
        }
    }

    return secondLargest === -Infinity ? -1 : secondLargest;
}

// Test Cases
console.log(secondLargest([10, 5, 20, 8])); // Output: 10
console.log(secondLargest([7, 7, 7])); // Output: -1
console.log(secondLargest([3])); // Output: -1

Time Complexity: O(n)O(n)


2. Linked List Problem (Easy)

Problem: Find the Middle Node of a Linked List

Given a singly linked list, return the middle node.
If there are two middle nodes, return the second one.

Example:

Input: 1 → 2 → 3 → 4 → 5
Output: 3

Input: 1 → 2 → 3 → 4 → 5 → 6
Output: 4

Solution (JavaScript)

class ListNode {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

function findMiddle(head) {
    let slow = head, fast = head;

    while (fast !== null && fast.next !== null) {
        slow = slow.next;  // Move slow one step
        fast = fast.next.next;  // Move fast two steps
    }

    return slow.val;
}

// Helper function to create a linked list
function createLinkedList(arr) {
    let head = new ListNode(arr[0]);
    let current = head;
    for (let i = 1; i < arr.length; i++) {
        current.next = new ListNode(arr[i]);
        current = current.next;
    }
    return head;
}

// Test Cases
let head1 = createLinkedList([1, 2, 3, 4, 5]);
console.log(findMiddle(head1)); // Output: 3

let head2 = createLinkedList([1, 2, 3, 4, 5, 6]);
console.log(findMiddle(head2)); // Output: 4

Time Complexity: O(n)O(n)


3. Map Problem (Easy)

Problem: Find First Non-Repeating Character

Given a string s, find the first non-repeating character and return its index.
If all characters repeat, return -1.

Example:

Input: "leetcode"
Output: 0  // ('l' is the first unique character)

Input: "aabb"
Output: -1  // (No unique character)

Solution (JavaScript)

function firstUniqueChar(s) {
    let charCount = new Map();

    // Count frequency of characters
    for (let char of s) {
        charCount.set(char, (charCount.get(char) || 0) + 1);
    }

    // Find the first unique character
    for (let i = 0; i < s.length; i++) {
        if (charCount.get(s[i]) === 1) return i;
    }

    return -1;
}

// Test Cases
console.log(firstUniqueChar("leetcode")); // Output: 0
console.log(firstUniqueChar("loveleetcode")); // Output: 2
console.log(firstUniqueChar("aabb")); // Output: -1

Time Complexity: O(n)O(n)


These problems are great for understanding Array, Linked List, and Map usage in JavaScript. Let me know if you need more! 🚀

How to clear RAM – Clear Cache – Drop Cache

The “1, 2, 3” cache clear method in Linux refers to clearing different types of caches managed by the operating system. Each cache type is managed differently and cleared by writing a specific value to the file /proc/sys/vm/drop_caches.

Cache Types:

  1. PageCache (Value: 1):
    • PageCache stores file contents that are cached in memory to reduce disk I/O.
  2. Dentries and Inodes (Value: 2):
    • Dentry is a cache of directory entries, and inodes store file metadata.
  3. PageCache + Dentries + Inodes (Value: 3):
    • Clears both PageCache and Dentry/inode caches.

Steps to Clear Cache with Examples:

1. Check Current Memory Usage

Use the free -h command to view current memory and cached memory:

free -h

Look under the “buff/cache” column to see the cache usage.

2. Clear Cache

Use the following commands to clear caches. Root privileges are required, so prefix with sudo:

Clear PageCache:
sudo sh -c "echo 1 > /proc/sys/vm/drop_caches"
Clear Dentry and Inode Cache:
sudo sh -c "echo 2 > /proc/sys/vm/drop_caches"
Clear Both PageCache and Dentry/Inode Cache:
sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"

3. Check Memory Usage Again

Run the free -h command again to verify that the cache has been cleared.

Example Workflow:

  1. Check Memory Before Clearing: free -h Output: total used free shared buff/cache available Mem: 15Gi 4.0Gi 2.0Gi 0.5Gi 9Gi 10Gi Swap: 2Gi 0B 2Gi
  2. Clear All Caches (PageCache, Dentries, and Inodes): sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"
  3. Check Memory After Clearing: free -h Output: total used free shared buff/cache available Mem: 15Gi 4.0Gi 7.0Gi 0.5Gi 4Gi 11Gi Swap: 2Gi 0B 2Gi

Notice how the “buff/cache” column decreases.

Best Practices

  • Clearing caches isn’t typically necessary because Linux uses unused memory to cache files and automatically clears it when needed.
  • Use this method only for debugging or specific needs (e.g., testing performance under no cache conditions).

Would you like to try this on your system now? Let me know if you need additional help!

Let’s break down PageCache, Dentries, and Inodes with simple explanations and commands you can use on your Ubuntu system to see how they work.


1. PageCache

  • What it is:
    • PageCache stores file data read from disk in memory to speed up future reads.
    • If a file is accessed again, the system reads it from memory instead of the slower disk.
  • Example:
    1. Create a Large File: dd if=/dev/zero of=testfile bs=1M count=100 This creates a file testfile of 100 MB size.
    2. Clear Cache: sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"
    3. Read the File (Populates PageCache): time cat testfile > /dev/null The first read is slow because it loads data from disk.
    4. Read the File Again (From PageCache): time cat testfile > /dev/null The second read is faster as it fetches data from memory (PageCache).
    5. Verify Cache Usage: Check memory usage using: free -h

2. Dentries

  • What it is:
    • A dentry (directory entry) cache stores metadata about directories, such as filenames and their locations in the filesystem.
    • This speeds up directory traversals and file lookups.
  • Example:
    1. Clear Cache: sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"
    2. List a Large Directory (Populates Dentry Cache): ls -R /usr > /dev/null
    3. List the Directory Again (From Dentry Cache): time ls -R /usr > /dev/null The second run will be faster because the directory structure is cached in memory.

3. Inodes

  • What it is:
    • An inode is a data structure storing metadata about a file (e.g., permissions, owner, size).
    • Inode caching stores this metadata to reduce disk reads.
  • Example:
    1. Find Inodes Used by the System: df -i This shows the inode usage for each mounted filesystem.
    2. Create Many Files (Populates Inode Cache): mkdir testdir for i in {1..10000}; do touch testdir/file$i; done
    3. Clear Cache: sudo sh -c "echo 2 > /proc/sys/vm/drop_caches"
    4. List Files (Rebuilds Inode Cache): time ls testdir > /dev/null
    5. List Files Again (From Inode Cache): time ls testdir > /dev/null The second run will be faster due to inode caching.

Summary of Commands:

  • free -h: Check memory usage (PageCache in “buff/cache”).
  • df -i: Check inode usage for filesystems.
  • echo [1|2|3] > /proc/sys/vm/drop_caches: Clear caches.

The command dd if=/dev/zero of=testfile bs=1M count=100 is a Linux command used to create a file filled with zeros. Here’s a breakdown of each part:

Command Breakdown:

  1. dd:
    • A low-level command-line utility used for copying and converting data between files or devices.
  2. if=/dev/zero:
    • if stands for “input file.”
    • /dev/zero is a special file in Linux that produces a continuous stream of null bytes (zeros).
  3. of=testfile:
    • of stands for “output file.”
    • testfile is the name of the file where the data (zeros) will be written.
  4. bs=1M:
    • bs stands for “block size.”
    • This sets the size of each block of data to 1 Megabyte (MB).
  5. count=100:
    • Specifies the number of blocks to copy.
    • In this case, 100 blocks of 1 MB each.

What the Command Does:

  • It writes 100 MB (1 MB × 100 blocks) of zero-filled data to a file named testfile.

Example Output:

When you run the command, you’ll see something like this:

100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.123456 s, 847 MB/s

This means:

  • 100+0 records in: 100 blocks read from the input file (/dev/zero).
  • 100+0 records out: 100 blocks written to the output file (testfile).
  • 104857600 bytes: Total bytes written (100 MB).
  • 0.123456 s: Time taken to execute the command.
  • 847 MB/s: Write speed.

Verify the File:

  • Check the file size: ls -lh testfile You should see the size as 100 MB.
  • Inspect the file contents: hexdump -C testfile | head This will display the file’s contents in hexadecimal format, and you’ll see it filled with 00 (zeros).

Why clearing dentries does not affect memory a lot

The behavior you’re observing can be explained by how Linux handles PageCache and Dentries/Inodes caching.

Key Points:

  1. PageCache (Cleared with echo 1 > /proc/sys/vm/drop_caches):
    • Clearing PageCache removes cached file data but does not clear dentries and inodes.
    • If you only clear the PageCache, Linux has to read file contents from disk, but dentry and inode information might still be available in memory.
  2. Dentries and Inodes (Cleared with echo 2 > /proc/sys/vm/drop_caches):
    • Clearing dentry and inode caches removes directory structure and file metadata information from memory.
    • If dentry and inode caches are cleared, listing directories or performing file operations becomes slower because the system must rebuild this information by reading from disk.

Your Test Results:

  1. Before Cache Clear:
    • The first ls -R command runs quickly (0.343s) because both PageCache and dentry/inode caches are populated.
  2. After Clearing PageCache:
    • After running echo 1 > /proc/sys/vm/drop_caches, the second ls -R command takes significantly longer (2.756s) because:
      • PageCache is cleared, so file contents must be reloaded from disk.
      • However, dentries and inodes are not cleared, so some metadata is still available.

Why It Still Takes More Time:

The additional time comes from the fact that:

  1. After clearing the PageCache, the system has to read the file contents (or parts of the directory structure) from disk, which is slower than fetching them from memory.
  2. Even though dentries and inodes are still in memory, they depend on PageCache for efficient access to file content. So the system has to do extra work to populate the PageCache again.
  3. Directory traversal involves a combination of file metadata (dentries/inodes) and directory file contents (loaded via PageCache). Clearing just the PageCache impacts this process.

Solution to Test Dentry Cache Impact:

To focus solely on dentry and inode caches, you need to clear them explicitly with:

sh -c "echo 2 > /proc/sys/vm/drop_caches"

Then rerun:

time ls -R /usr > /dev/null

You’ll notice that this run will also take longer compared to when the dentry cache is intact, but the pattern will differ from clearing the PageCache.


Suggested Workflow to Understand All Cache Impacts:

  1. Baseline: time ls -R /usr > /dev/null
  2. Clear PageCache: sh -c "echo 1 > /proc/sys/vm/drop_caches" time ls -R /usr > /dev/null
  3. Clear Dentries and Inodes: sh -c "echo 2 > /proc/sys/vm/drop_caches" time ls -R /usr > /dev/null
  4. Clear Both PageCache and Dentries/Inodes: sh -c "echo 3 > /proc/sys/vm/drop_caches" time ls -R /usr > /dev/null

This should give you a clear understanding of how each type of cache contributes to performance.

inotify

You can watch realtime operations happing in directory using inotifywatch and inotifywait command

Install inotify tool

sudo apt install inotify-tools

Create directory

mkdir -p /tmp/test

Watch action

inotifywatch -v -e modify,create,delete /tmp/test

Ctrl + C

#Then check statistics

Real time watch action

inotifywait -m -e modify,create,delete /tmp/test/
inotifywait -m -r -e modify,create,delete /tmp/test/

Now try to create modify and delete the file

touch /tmp/test/file1.txt
echo "Hello" > /tmp/test/file1.txt
rm /tmp/test/file1.txt

Ctrl + C
Left terminal to watch activities and right one to run commands

To monitor multiple paths at a time run following commands

inotifywatch -e access,modify /home/user/myfolder /home/user/another_folder /home/user/myfile.txt
OR
inotifywait -m -e access,modify /home/user/myfolder /home/user/another_folder /home/user/myfile.txt