๐Ÿ“Š Array Hack Challenge Progress Tracker

๐ŸŽฏ Your Learning Journey

๐Ÿ“ˆ Overall Progress

0% Complete

๐Ÿ—บ๏ธ Learning Milestones

โญ• ๐ŸŽฏ Array Fundamentals
Basic memory systems & operations
โญ• ๐Ÿงฎ Advanced Features
Multi-number operations & classes
โญ• ๐Ÿ“Š Statistical Computing
Mean, median, mode calculations
โญ• ๐ŸŽฎ Interactive Features
History tracking & undo/redo
โญ• ๐Ÿ”ฌ Matrix Operations
2D arrays & linear algebra
โญ• ๐Ÿ† Challenge Projects
Scientific & financial calculators
โญ• ๐Ÿ’ก Pro Tips
Performance optimization
โญ• ๐Ÿš€ Final Integration
Complete calculator build

๐ŸŽฏ Quick Actions


๐Ÿ”ง Array Hack Challenge: Building Better Calculators

Welcome to the ultimate guide on using Arrays to supercharge your calculator applications! Letโ€™s explore how arrays can transform your basic calculator into a powerful computational tool.


๐Ÿš€ Why Arrays Make Calculators Amazing

Arrays are the secret weapon for creating professional calculators. Hereโ€™s why:

  • ๐Ÿ“œ History Tracking - Store every calculation
  • ๐Ÿ”ข Multi-Number Operations - Work with sets of data
  • ๐Ÿ“Š Statistical Functions - Mean, median, mode calculations
  • ๐Ÿ’พ Memory Functions - Save and recall values
  • ๐ŸŽฏ Advanced Operations - Matrix math, sequences, and more

๐ŸŽฏ Calculator Array Fundamentals

Basic Calculator Memory System

// Calculator memory using arrays
let calculatorMemory = [];
let calculationHistory = [];
let currentNumbers = [];

// Store a calculation
function storeCalculation(operation, result) {
    calculationHistory.push({
        operation: operation,
        result: result,
        timestamp: new Date().toLocaleString()
    });
}

// Memory functions
function memoryStore(value) {
    calculatorMemory.push(value);
    console.log(`Stored: ${value}`);
}

function memoryRecall() {
    return calculatorMemory.length > 0 ? 
           calculatorMemory[calculatorMemory.length - 1] : 0;
}

function memoryClear() {
    calculatorMemory = [];
    console.log("Memory cleared!");
}

๐Ÿ“– Line-by-Line Explanation: Basic Memory System

Letโ€™s break down every line of the memory system code:

let calculatorMemory = [];
  • let - Declares a variable that can be changed later
  • calculatorMemory - Variable name for storing calculator memory values
  • = - Assignment operator
  • [] - Creates an empty array to hold memory values
  • ; - Statement terminator
let calculationHistory = [];
  • Creates another empty array specifically for storing past calculations
  • This will hold objects containing operation details
let currentNumbers = [];
  • Array to hold numbers currently being worked with
  • Useful for multi-number operations
function storeCalculation(operation, result) {
  • function - Keyword to declare a function
  • storeCalculation - Function name describing what it does
  • (operation, result) - Parameters: the math operation and its result
  • { - Opens the function body
    calculationHistory.push({
  • calculationHistory - Our array for storing calculations
  • .push() - Array method that adds elements to the end
  • ({ - Opens an object literal to store calculation data
        operation: operation,
        result: result,
        timestamp: new Date().toLocaleString()
  • operation: operation - Stores the math operation (like โ€œ5 + 3โ€)
  • result: result - Stores the calculated result (like 8)
  • timestamp: - Property to store when calculation happened
  • new Date() - Creates a new date object with current time
  • .toLocaleString() - Converts date to readable text format
    });
}
  • }); - Closes the object and the push() method call
  • } - Closes the function
function memoryStore(value) {
    calculatorMemory.push(value);
    console.log(`Stored: ${value}`);
}

Line-by-line breakdown:

  • function memoryStore(value) - Function to save a value to memory
  • calculatorMemory.push(value) - Adds the value to end of memory array
  • console.log() - Prints confirmation message to console
  • `Stored: ${value}` - Template literal showing stored value
function memoryRecall() {
    return calculatorMemory.length > 0 ? 
           calculatorMemory[calculatorMemory.length - 1] : 0;
}

Detailed explanation:

  • function memoryRecall() - Function with no parameters to get last stored value
  • return - Sends a value back when function is called
  • calculatorMemory.length > 0 - Checks if array has any elements
  • ? - Ternary operator (if-then-else in one line)
  • calculatorMemory[calculatorMemory.length - 1] - Gets last array element
    • calculatorMemory.length - Total number of elements
    • - 1 - Subtract 1 because arrays start at index 0
  • : 0 - If array is empty, return 0 instead

Example Usage:

// Using our calculator arrays
storeCalculation("5 + 3", 8);
storeCalculation("10 * 2", 20);
memoryStore(42);

console.log("Last calculation:", calculationHistory[calculationHistory.length - 1]);
console.log("Memory recall:", memoryRecall());

Usage explanation:

  • storeCalculation("5 + 3", 8) - Stores addition operation and result
  • storeCalculation("10 * 2", 20) - Stores multiplication operation and result
  • memoryStore(42) - Saves number 42 to calculator memory
  • calculationHistory[calculationHistory.length - 1] - Accesses last calculation
  • memoryRecall() - Calls function to get last stored memory value

๐Ÿงฎ Advanced Calculator Features with Arrays

1. Multi-Number Operations

class ArrayCalculator {
    constructor() {
        this.numbers = [];
        this.results = [];
    }
    
    // Add numbers to calculation set
    addNumbers(...nums) {
        this.numbers.push(...nums);
        return this;
    }
    
    // Calculate sum of all numbers
    calculateSum() {
        const sum = this.numbers.reduce((total, num) => total + num, 0);
        this.results.push({ operation: 'sum', result: sum, numbers: [...this.numbers] });
        return sum;
    }
    
    // Calculate average
    calculateAverage() {
        const sum = this.calculateSum();
        const avg = sum / this.numbers.length;
        this.results.push({ operation: 'average', result: avg, numbers: [...this.numbers] });
        return avg;
    }
    
    // Find maximum value
    findMax() {
        const max = Math.max(...this.numbers);
        this.results.push({ operation: 'max', result: max, numbers: [...this.numbers] });
        return max;
    }
    
    // Find minimum value
    findMin() {
        const min = Math.min(...this.numbers);
        this.results.push({ operation: 'min', result: min, numbers: [...this.numbers] });
        return min;
    }
    
    // Clear numbers for next calculation
    clear() {
        this.numbers = [];
        return this;
    }
    
    // Get calculation history
    getHistory() {
        return this.results;
    }
}

๐Ÿ“– Line-by-Line Explanation: Array Calculator

class ArrayCalculator {
  • class - JavaScript keyword to create a blueprint for objects
  • ArrayCalculator - Name of our class (like a template for calculators)
  • { - Opens the class definition
    constructor() {
        this.numbers = [];
        this.results = [];
    }
  • constructor() - Special function that runs when creating new calculator
  • this.numbers = [] - Creates empty array for current numbers
    • this - Refers to the specific calculator object being created
    • .numbers - Property name for storing numbers
  • this.results = [] - Creates empty array for storing calculation results
    addNumbers(...nums) {
        this.numbers.push(...nums);
        return this;
    }

Detailed breakdown:

  • addNumbers(...nums) - Method to add multiple numbers at once
    • ...nums - Rest parameter that collects all arguments into an array
  • this.numbers.push(...nums) - Adds all numbers to our array
    • ...nums - Spread operator that unpacks the array of numbers
  • return this - Returns the calculator object for method chaining
    calculateSum() {
        const sum = this.numbers.reduce((total, num) => total + num, 0);
        this.results.push({ operation: 'sum', result: sum, numbers: [...this.numbers] });
        return sum;
    }

Line-by-line analysis:

  • calculateSum() - Method to add all numbers together
  • const sum = - Creates unchangeable variable for the sum
  • this.numbers.reduce() - Array method that combines all elements
  • (total, num) => total + num - Arrow function that adds current number to total
    • total - Accumulator that keeps running total
    • num - Current number being processed
    • => - Arrow function syntax
    • total + num - Addition operation
  • , 0 - Starting value for the accumulator
  • this.results.push({...}) - Saves calculation details to history
  • numbers: [...this.numbers] - Creates copy of numbers array using spread operator
    calculateAverage() {
        const sum = this.calculateSum();
        const avg = sum / this.numbers.length;
        this.results.push({ operation: 'average', result: avg, numbers: [...this.numbers] });
        return avg;
    }

Step-by-step explanation:

  • const sum = this.calculateSum() - Calls our sum method to get total
  • const avg = sum / this.numbers.length - Divides sum by count of numbers
    • this.numbers.length - Property that gives array size
    • / - Division operator
  • Records the average calculation in results history
  • return avg - Sends back the calculated average
    findMax() {
        const max = Math.max(...this.numbers);
        this.results.push({ operation: 'max', result: max, numbers: [...this.numbers] });
        return max;
    }

Explanation:

  • Math.max() - Built-in JavaScript function to find largest number
  • ...this.numbers - Spread operator passes all array elements as separate arguments
  • Example: Math.max(...[1,2,3]) becomes Math.max(1,2,3)

Usage Example:

const calc = new ArrayCalculator();

// Add multiple numbers and perform operations
calc.addNumbers(10, 25, 30, 15, 40)
    .calculateSum()     // Returns: 120
    .calculateAverage() // Returns: 24
    .findMax()         // Returns: 40
    .findMin();        // Returns: 10

console.log("All results:", calc.getHistory());

Usage breakdown:

  • const calc = new ArrayCalculator() - Creates new calculator instance
    • new - Keyword to create object from class
  • calc.addNumbers(10, 25, 30, 15, 40) - Adds 5 numbers to calculator
  • .calculateSum() - Method chaining: calls sum on same object
  • Method chaining works because each method returns this

๐Ÿ“Š Statistical Calculator Functions

Advanced Statistics with Arrays

class StatisticalCalculator {
    constructor() {
        this.dataset = [];
    }
    
    // Add data points
    addData(values) {
        if (Array.isArray(values)) {
            this.dataset.push(...values);
        } else {
            this.dataset.push(values);
        }
        return this;
    }
    
    // Calculate mean (average)
    mean() {
        return this.dataset.reduce((sum, val) => sum + val, 0) / this.dataset.length;
    }
    
    // Calculate median (middle value)
    median() {
        const sorted = [...this.dataset].sort((a, b) => a - b);
        const mid = Math.floor(sorted.length / 2);
        
        return sorted.length % 2 !== 0 
            ? sorted[mid] 
            : (sorted[mid - 1] + sorted[mid]) / 2;
    }
    
    // Calculate mode (most frequent value)
    mode() {
        const frequency = {};
        let maxFreq = 0;
        let modes = [];
        
        // Count frequencies
        this.dataset.forEach(val => {
            frequency[val] = (frequency[val] || 0) + 1;
            if (frequency[val] > maxFreq) {
                maxFreq = frequency[val];
            }
        });
        
        // Find all values with max frequency
        for (let val in frequency) {
            if (frequency[val] === maxFreq) {
                modes.push(Number(val));
            }
        }
        
        return modes.length === this.dataset.length ? [] : modes;
    }
    
    // Calculate standard deviation
    standardDeviation() {
        const mean = this.mean();
        const squaredDiffs = this.dataset.map(val => Math.pow(val - mean, 2));
        const avgSquaredDiff = squaredDiffs.reduce((sum, val) => sum + val, 0) / this.dataset.length;
        return Math.sqrt(avgSquaredDiff);
    }
    
    // Get data summary
    getSummary() {
        return {
            data: [...this.dataset],
            count: this.dataset.length,
            mean: this.mean(),
            median: this.median(),
            mode: this.mode(),
            standardDeviation: this.standardDeviation(),
            min: Math.min(...this.dataset),
            max: Math.max(...this.dataset)
        };
    }
}

๐Ÿ“– Line-by-Line Explanation: Statistical Calculator

    addData(values) {
        if (Array.isArray(values)) {
            this.dataset.push(...values);
        } else {
            this.dataset.push(values);
        }
        return this;
    }

Detailed breakdown:

  • addData(values) - Method to add data points to our dataset
  • if (Array.isArray(values)) - Checks if input is an array
    • Array.isArray() - Built-in function to test if something is an array
  • this.dataset.push(...values) - If array, spread elements and add each one
  • else - If not an array (single value)
  • this.dataset.push(values) - Add the single value directly
    mean() {
        return this.dataset.reduce((sum, val) => sum + val, 0) / this.dataset.length;
    }

Step-by-step:

  • mean() - Method to calculate average (mean)
  • this.dataset.reduce((sum, val) => sum + val, 0) - Adds all values
    • sum - Running total
    • val - Current value being processed
    • 0 - Starting value for sum
  • / this.dataset.length - Divides total by count of values
    median() {
        const sorted = [...this.dataset].sort((a, b) => a - b);
        const mid = Math.floor(sorted.length / 2);
        
        return sorted.length % 2 !== 0 
            ? sorted[mid] 
            : (sorted[mid - 1] + sorted[mid]) / 2;
    }

Comprehensive explanation:

  • const sorted = [...this.dataset].sort((a, b) => a - b) - Sorts data
    • [...this.dataset] - Creates copy so original isnโ€™t changed
    • .sort((a, b) => a - b) - Sorts numbers in ascending order
    • a - b - Comparison function: negative = a first, positive = b first
  • const mid = Math.floor(sorted.length / 2) - Finds middle index
    • Math.floor() - Rounds down to nearest integer
  • sorted.length % 2 !== 0 - Checks if odd number of values
    • % - Modulo operator (remainder after division)
    • !== 0 - Not equal to zero (odd numbers have remainder 1)
  • ? sorted[mid] - If odd, return middle value
  • : (sorted[mid - 1] + sorted[mid]) / 2 - If even, average two middle values
    mode() {
        const frequency = {};
        let maxFreq = 0;
        let modes = [];
        
        // Count frequencies
        this.dataset.forEach(val => {
            frequency[val] = (frequency[val] || 0) + 1;
            if (frequency[val] > maxFreq) {
                maxFreq = frequency[val];
            }
        });
        
        // Find all values with max frequency
        for (let val in frequency) {
            if (frequency[val] === maxFreq) {
                modes.push(Number(val));
            }
        }
        
        return modes.length === this.dataset.length ? [] : modes;
    }

Mode calculation breakdown:

  • const frequency = {} - Object to count how often each value appears
  • let maxFreq = 0 - Variable to track highest frequency
  • let modes = [] - Array to store most frequent values
  • this.dataset.forEach(val => { - Loop through each data value
  • frequency[val] = (frequency[val] || 0) + 1 - Count occurrences
    • frequency[val] - Get current count for this value
    • || 0 - If undefined, use 0 instead
    • + 1 - Add 1 to the count
  • if (frequency[val] > maxFreq) - If this is new highest frequency
  • maxFreq = frequency[val] - Update maximum frequency
  • for (let val in frequency) - Loop through all counted values
  • if (frequency[val] === maxFreq) - If value has maximum frequency
  • modes.push(Number(val)) - Add to modes array
    • Number(val) - Convert string back to number
  • modes.length === this.dataset.length ? [] : modes - Return empty if all values appear once

Statistics Example:

const stats = new StatisticalCalculator();
stats.addData([85, 90, 78, 92, 88, 85, 95, 82, 90, 87]);

console.log("Dataset Summary:");
console.log(stats.getSummary());
// Output: Complete statistical analysis of the dataset

Example explanation:

  • new StatisticalCalculator() - Creates new statistics calculator
  • stats.addData([85, 90, 78, 92, 88, 85, 95, 82, 90, 87]) - Adds test scores
  • stats.getSummary() - Calls method that returns object with all statistics

๐ŸŽฎ Interactive Calculator Features

Calculator History with Undo/Redo

class HistoryCalculator {
    constructor() {
        this.history = [];
        this.currentIndex = -1;
        this.currentValue = 0;
    }
    
    // Perform operation and save to history
    calculate(operation, operand) {
        let result;
        
        switch(operation) {
            case '+': result = this.currentValue + operand; break;
            case '-': result = this.currentValue - operand; break;
            case '*': result = this.currentValue * operand; break;
            case '/': result = operand !== 0 ? this.currentValue / operand : 'Error'; break;
            case '=': result = operand; break;
            default: result = this.currentValue;
        }
        
        // Add to history (remove any future history if we're in the middle)
        this.history = this.history.slice(0, this.currentIndex + 1);
        this.history.push({
            operation: `${this.currentValue} ${operation} ${operand}`,
            result: result,
            timestamp: Date.now()
        });
        
        this.currentIndex++;
        this.currentValue = result;
        
        return result;
    }
    
    // Undo last operation
    undo() {
        if (this.currentIndex > 0) {
            this.currentIndex--;
            this.currentValue = this.history[this.currentIndex].result;
            return this.currentValue;
        }
        return "Cannot undo further";
    }
    
    // Redo operation
    redo() {
        if (this.currentIndex < this.history.length - 1) {
            this.currentIndex++;
            this.currentValue = this.history[this.currentIndex].result;
            return this.currentValue;
        }
        return "Cannot redo further";
    }
    
    // Get full history
    getHistory() {
        return this.history.map((entry, index) => ({
            ...entry,
            current: index === this.currentIndex
        }));
    }
    
    // Clear all history
    clearHistory() {
        this.history = [];
        this.currentIndex = -1;
        this.currentValue = 0;
    }
}

๐Ÿ“– Line-by-Line Explanation: History Calculator

    constructor() {
        this.history = [];
        this.currentIndex = -1;
        this.currentValue = 0;
    }

Constructor breakdown:

  • this.history = [] - Array to store all calculation steps
  • this.currentIndex = -1 - Points to current position in history (-1 = no history yet)
  • this.currentValue = 0 - Stores current calculator display value
    calculate(operation, operand) {
        let result;
        
        switch(operation) {
            case '+': result = this.currentValue + operand; break;
            case '-': result = this.currentValue - operand; break;
            case '*': result = this.currentValue * operand; break;
            case '/': result = operand !== 0 ? this.currentValue / operand : 'Error'; break;
            case '=': result = operand; break;
            default: result = this.currentValue;
        }

Calculate method explanation:

  • calculate(operation, operand) - Method to perform math operations
  • let result - Variable to store calculation result
  • switch(operation) - Checks which operation to perform
  • case '+' - If operation is addition
  • result = this.currentValue + operand - Add current value and operand
  • break - Exit switch statement
  • case '/' - Division case with error checking
  • operand !== 0 - Check if not dividing by zero
  • ? this.currentValue / operand - If safe, do division
  • : 'Error' - Otherwise, return error message
  • default: - If operation not recognized, keep current value
        // Add to history (remove any future history if we're in the middle)
        this.history = this.history.slice(0, this.currentIndex + 1);
        this.history.push({
            operation: `${this.currentValue} ${operation} ${operand}`,
            result: result,
            timestamp: Date.now()
        });
        
        this.currentIndex++;
        this.currentValue = result;
        
        return result;

History management:

  • this.history.slice(0, this.currentIndex + 1) - Removes future history
    • If user was in middle of history and does new operation
    • slice() creates new array with only elements up to current position
  • this.history.push({...}) - Adds new calculation to history
  • `${this.currentValue} ${operation} ${operand}` - Template literal for operation string
  • timestamp: Date.now() - Records when calculation happened
  • this.currentIndex++ - Move to new position in history
  • this.currentValue = result - Update calculator display
    undo() {
        if (this.currentIndex > 0) {
            this.currentIndex--;
            this.currentValue = this.history[this.currentIndex].result;
            return this.currentValue;
        }
        return "Cannot undo further";
    }

Undo functionality:

  • if (this.currentIndex > 0) - Check if thereโ€™s something to undo
  • this.currentIndex-- - Move back one step in history
  • this.currentValue = this.history[this.currentIndex].result - Restore previous result
  • return "Cannot undo further" - Message when no more undo available

๐Ÿ”ฌ Matrix Calculator with Arrays

2D Arrays for Matrix Operations

class MatrixCalculator {
    constructor() {
        this.matrices = [];
    }
    
    // Create a new matrix
    createMatrix(rows, cols, fillValue = 0) {
        const matrix = [];
        for (let i = 0; i < rows; i++) {
            matrix[i] = [];
            for (let j = 0; j < cols; j++) {
                matrix[i][j] = fillValue;
            }
        }
        return matrix;
    }
    
    // Add two matrices
    addMatrices(matrix1, matrix2) {
        if (matrix1.length !== matrix2.length || 
            matrix1[0].length !== matrix2[0].length) {
            throw new Error("Matrices must have same dimensions");
        }
        
        const result = [];
        for (let i = 0; i < matrix1.length; i++) {
            result[i] = [];
            for (let j = 0; j < matrix1[i].length; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }
        return result;
    }
    
    // Multiply two matrices
    multiplyMatrices(matrix1, matrix2) {
        if (matrix1[0].length !== matrix2.length) {
            throw new Error("Invalid dimensions for multiplication");
        }
        
        const result = this.createMatrix(matrix1.length, matrix2[0].length);
        
        for (let i = 0; i < matrix1.length; i++) {
            for (let j = 0; j < matrix2[0].length; j++) {
                for (let k = 0; k < matrix2.length; k++) {
                    result[i][j] += matrix1[i][k] * matrix2[k][j];
                }
            }
        }
        return result;
    }
    
    // Display matrix nicely
    displayMatrix(matrix) {
        return matrix.map(row => 
            row.map(cell => cell.toString().padStart(6)).join(' ')
        ).join('\n');
    }
}

๐Ÿ“– Line-by-Line Explanation: Matrix Calculator

    createMatrix(rows, cols, fillValue = 0) {
        const matrix = [];
        for (let i = 0; i < rows; i++) {
            matrix[i] = [];
            for (let j = 0; j < cols; j++) {
                matrix[i][j] = fillValue;
            }
        }
        return matrix;
    }

Matrix creation breakdown:

  • createMatrix(rows, cols, fillValue = 0) - Method to create new matrix
    • fillValue = 0 - Default parameter: use 0 if no value provided
  • const matrix = [] - Create empty array for the matrix
  • for (let i = 0; i < rows; i++) - Loop for each row
    • i - Row counter starting at 0
    • i < rows - Continue while i is less than number of rows
    • i++ - Increment i after each iteration
  • matrix[i] = [] - Create empty array for current row
  • for (let j = 0; j < cols; j++) - Inner loop for each column
    • j - Column counter
  • matrix[i][j] = fillValue - Set value at row i, column j
    • matrix[i] - Access the row array
    • [j] - Access specific column in that row
    addMatrices(matrix1, matrix2) {
        if (matrix1.length !== matrix2.length || 
            matrix1[0].length !== matrix2[0].length) {
            throw new Error("Matrices must have same dimensions");
        }
        
        const result = [];
        for (let i = 0; i < matrix1.length; i++) {
            result[i] = [];
            for (let j = 0; j < matrix1[i].length; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }
        return result;
    }

Matrix addition explanation:

  • if (matrix1.length !== matrix2.length || - Check if same number of rows
    • !== - Strict inequality operator
    • || - Logical OR operator
  • matrix1[0].length !== matrix2[0].length) - Check if same number of columns
    • matrix1[0] - First row of matrix1
    • .length - Number of columns in first row
  • throw new Error("...") - Stops execution and shows error message
  • result[i][j] = matrix1[i][j] + matrix2[i][j] - Adds corresponding elements
    • Takes element from same position in both matrices and adds them
    displayMatrix(matrix) {
        return matrix.map(row => 
            row.map(cell => cell.toString().padStart(6)).join(' ')
        ).join('\n');
    }

Display formatting breakdown:

  • matrix.map(row => - Transform each row of the matrix
  • row.map(cell => - Transform each cell in the row
  • cell.toString() - Convert number to string
  • .padStart(6) - Add spaces to make string 6 characters wide
  • .join(' ') - Combine cells in row with spaces between
  • .join('\n') - Combine rows with newlines between

Matrix Example:

const matrixCalc = new MatrixCalculator();

const matrix1 = [[1, 2], [3, 4]];
const matrix2 = [[5, 6], [7, 8]];

const sum = matrixCalc.addMatrices(matrix1, matrix2);
const product = matrixCalc.multiplyMatrices(matrix1, matrix2);

console.log("Matrix Addition:");
console.log(matrixCalc.displayMatrix(sum));

console.log("Matrix Multiplication:");
console.log(matrixCalc.displayMatrix(product));

Matrix example explanation:

  • const matrix1 = [[1, 2], [3, 4]] - 2x2 matrix using nested arrays
    • [1, 2] - First row
    • [3, 4] - Second row
  • const sum = matrixCalc.addMatrices(matrix1, matrix2) - Add matrices element by element
  • matrixCalc.displayMatrix(sum) - Format matrix for readable output

๐ŸŽฒ Random Number Generator with Arrays

Advanced Random Functions

class RandomCalculator {
    constructor() {
        this.generatedNumbers = [];
        this.seeds = [];
    }
    
    // Generate random integers in range
    generateIntegers(count, min, max) {
        const numbers = [];
        for (let i = 0; i < count; i++) {
            const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
            numbers.push(randomInt);
        }
        this.generatedNumbers.push(...numbers);
        return numbers;
    }
    
    // Generate random decimals
    generateDecimals(count, min, max, precision = 2) {
        const numbers = [];
        for (let i = 0; i < count; i++) {
            const randomDecimal = (Math.random() * (max - min) + min).toFixed(precision);
            numbers.push(parseFloat(randomDecimal));
        }
        this.generatedNumbers.push(...numbers);
        return numbers;
    }
    
    // Shuffle an array (Fisher-Yates algorithm)
    shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }
    
    // Pick random elements from array
    pickRandom(array, count = 1) {
        const shuffled = this.shuffleArray(array);
        return shuffled.slice(0, count);
    }
    
    // Generate random sequence
    generateSequence(start, step, count) {
        const sequence = [];
        let current = start;
        for (let i = 0; i < count; i++) {
            sequence.push(current);
            current += step + Math.floor(Math.random() * 3); // Add some randomness to step
        }
        return sequence;
    }
    
    // Get statistics of generated numbers
    getStats() {
        if (this.generatedNumbers.length === 0) return null;
        
        const sorted = [...this.generatedNumbers].sort((a, b) => a - b);
        return {
            count: this.generatedNumbers.length,
            min: sorted[0],
            max: sorted[sorted.length - 1],
            mean: this.generatedNumbers.reduce((sum, n) => sum + n, 0) / this.generatedNumbers.length,
            numbers: [...this.generatedNumbers]
        };
    }
}

๐Ÿ“– Line-by-Line Explanation: Random Number Generator

    generateIntegers(count, min, max) {
        const numbers = [];
        for (let i = 0; i < count; i++) {
            const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
            numbers.push(randomInt);
        }
        this.generatedNumbers.push(...numbers);
        return numbers;
    }

Random integer generation:

  • generateIntegers(count, min, max) - Method to create random whole numbers
  • const numbers = [] - Array to collect generated numbers
  • for (let i = 0; i < count; i++) - Loop to generate โ€˜countโ€™ numbers
  • Math.random() - Generates decimal between 0 and 1
  • Math.random() * (max - min + 1) - Scale to desired range
    • (max - min + 1) - Range size (inclusive of both min and max)
  • Math.floor(...) - Rounds down to nearest integer
  • + min - Shifts range to start at minimum value
  • Example: For min=1, max=6: Math.floor(Math.random() * 6) + 1 gives 1-6
    generateDecimals(count, min, max, precision = 2) {
        const numbers = [];
        for (let i = 0; i < count; i++) {
            const randomDecimal = (Math.random() * (max - min) + min).toFixed(precision);
            numbers.push(parseFloat(randomDecimal));
        }
        this.generatedNumbers.push(...numbers);
        return numbers;
    }

Random decimal generation:

  • precision = 2 - Default to 2 decimal places
  • Math.random() * (max - min) + min - Scale random number to range
  • .toFixed(precision) - Rounds to specified decimal places and converts to string
  • parseFloat(randomDecimal) - Converts string back to number
    shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

Fisher-Yates shuffle algorithm:

  • const shuffled = [...array] - Create copy to avoid modifying original
  • for (let i = shuffled.length - 1; i > 0; i--) - Loop backwards through array
    • Start from last element, go down to index 1
  • const j = Math.floor(Math.random() * (i + 1)) - Pick random index from 0 to i
  • [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]] - Swap elements
    • Array destructuring assignment to swap values
    • Swaps element at position i with element at random position j
    pickRandom(array, count = 1) {
        const shuffled = this.shuffleArray(array);
        return shuffled.slice(0, count);
    }

Random selection:

  • count = 1 - Default to picking 1 element
  • this.shuffleArray(array) - First shuffle the array
  • shuffled.slice(0, count) - Take first โ€˜countโ€™ elements from shuffled array
    • slice(0, count) - Creates new array with elements from index 0 to count-1

๐Ÿ† Calculator Challenge Projects

Challenge 1: Scientific Calculator Array

// Build a calculator that handles scientific functions with arrays
class ScientificCalculator {
    constructor() {
        this.angleMode = 'degrees'; // or 'radians'
        this.constants = {
            PI: Math.PI,
            E: Math.E,
            GOLDEN_RATIO: (1 + Math.sqrt(5)) / 2
        };
        this.history = [];
    }
    
    // Convert degrees to radians if needed
    toRadians(angle) {
        return this.angleMode === 'degrees' ? angle * (Math.PI / 180) : angle;
    }
    
    // Trigonometric functions
    sin(angle) { return Math.sin(this.toRadians(angle)); }
    cos(angle) { return Math.cos(this.toRadians(angle)); }
    tan(angle) { return Math.tan(this.toRadians(angle)); }
    
    // Array-based factorial
    factorial(n) {
        if (n < 0) return null;
        if (n <= 1) return 1;
        
        let result = 1;
        for (let i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }
    
    // Fibonacci sequence using arrays
    fibonacci(n) {
        if (n <= 0) return [];
        if (n === 1) return [0];
        if (n === 2) return [0, 1];
        
        const fib = [0, 1];
        for (let i = 2; i < n; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }
        return fib;
    }
    
    // Calculate polynomial with coefficients array
    polynomial(coefficients, x) {
        let result = 0;
        for (let i = 0; i < coefficients.length; i++) {
            result += coefficients[i] * Math.pow(x, coefficients.length - 1 - i);
        }
        return result;
    }
}

๐Ÿ“– Line-by-Line Explanation: Scientific Calculator

    constructor() {
        this.angleMode = 'degrees'; // or 'radians'
        this.constants = {
            PI: Math.PI,
            E: Math.E,
            GOLDEN_RATIO: (1 + Math.sqrt(5)) / 2
        };
        this.history = [];
    }

Scientific calculator setup:

  • this.angleMode = 'degrees' - Set default angle measurement
  • this.constants = {...} - Object storing mathematical constants
  • PI: Math.PI - Pi constant (approximately 3.14159)
  • E: Math.E - Eulerโ€™s number (approximately 2.71828)
  • GOLDEN_RATIO: (1 + Math.sqrt(5)) / 2 - Golden ratio calculation
    • Math.sqrt(5) - Square root of 5
    • (1 + ...) / 2 - Golden ratio formula
    toRadians(angle) {
        return this.angleMode === 'degrees' ? angle * (Math.PI / 180) : angle;
    }

Angle conversion:

  • this.angleMode === 'degrees' - Check if calculator is in degree mode
  • ? angle * (Math.PI / 180) - If degrees, convert to radians
    • Multiply by ฯ€/180 to convert degrees to radians
  • : angle - If already in radians, return unchanged
    factorial(n) {
        if (n < 0) return null;
        if (n <= 1) return 1;
        
        let result = 1;
        for (let i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

Factorial calculation:

  • if (n < 0) return null - Factorial undefined for negative numbers
  • if (n <= 1) return 1 - Base cases: 0! = 1, 1! = 1
  • let result = 1 - Initialize result
  • for (let i = 2; i <= n; i++) - Loop from 2 to n
  • result *= i - Multiply result by current number
    • *= is shorthand for result = result * i
    fibonacci(n) {
        if (n <= 0) return [];
        if (n === 1) return [0];
        if (n === 2) return [0, 1];
        
        const fib = [0, 1];
        for (let i = 2; i < n; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }
        return fib;
    }

Fibonacci sequence generation:

  • if (n <= 0) return [] - Return empty array for invalid input
  • if (n === 1) return [0] - First Fibonacci number is 0
  • if (n === 2) return [0, 1] - First two Fibonacci numbers
  • const fib = [0, 1] - Initialize array with first two numbers
  • fib[i] = fib[i - 1] + fib[i - 2] - Each number is sum of previous two
    • fib[i - 1] - Previous number in sequence
    • fib[i - 2] - Number before that
    polynomial(coefficients, x) {
        let result = 0;
        for (let i = 0; i < coefficients.length; i++) {
            result += coefficients[i] * Math.pow(x, coefficients.length - 1 - i);
        }
        return result;
    }

Polynomial evaluation:

  • polynomial(coefficients, x) - Evaluate polynomial at value x
  • coefficients - Array of polynomial coefficients [a, b, c, d] for axยณ + bxยฒ + cx + d
  • for (let i = 0; i < coefficients.length; i++) - Loop through coefficients
  • coefficients[i] - Current coefficient
  • Math.pow(x, coefficients.length - 1 - i) - x raised to appropriate power
    • coefficients.length - 1 - i - Calculate power (highest power first)
  • result += ... - Add term to running total

Challenge 2: Financial Calculator

class FinancialCalculator {
    constructor() {
        this.transactions = [];
        this.rates = [];
    }
    
    // Compound interest calculation
    compoundInterest(principal, rate, time, frequency = 12) {
        const amount = principal * Math.pow(1 + rate / frequency, frequency * time);
        return {
            principal: principal,
            amount: amount,
            interest: amount - principal,
            rate: rate,
            time: time
        };
    }
    
    // Loan payment calculator
    loanPayment(principal, rate, payments) {
        const monthlyRate = rate / 12;
        const payment = principal * (monthlyRate * Math.pow(1 + monthlyRate, payments)) / 
                       (Math.pow(1 + monthlyRate, payments) - 1);
        
        // Generate amortization schedule
        const schedule = [];
        let balance = principal;
        
        for (let i = 1; i <= payments; i++) {
            const interestPayment = balance * monthlyRate;
            const principalPayment = payment - interestPayment;
            balance -= principalPayment;
            
            schedule.push({
                payment: i,
                paymentAmount: payment,
                principal: principalPayment,
                interest: interestPayment,
                balance: Math.max(0, balance)
            });
        }
        
        return schedule;
    }
    
    // Investment return calculator
    investmentGrowth(initialInvestment, monthlyContribution, annualReturn, years) {
        const monthlyReturn = annualReturn / 12;
        const months = years * 12;
        const growth = [];
        
        let balance = initialInvestment;
        
        for (let month = 1; month <= months; month++) {
            balance += monthlyContribution;
            balance *= (1 + monthlyReturn);
            
            if (month % 12 === 0) {
                growth.push({
                    year: month / 12,
                    balance: balance,
                    totalContributions: initialInvestment + (monthlyContribution * month),
                    earnings: balance - (initialInvestment + monthlyContribution * month)
                });
            }
        }
        
        return growth;
    }
}

๐Ÿ“– Line-by-Line Explanation: Financial Calculator

    compoundInterest(principal, rate, time, frequency = 12) {
        const amount = principal * Math.pow(1 + rate / frequency, frequency * time);
        return {
            principal: principal,
            amount: amount,
            interest: amount - principal,
            rate: rate,
            time: time
        };
    }

Compound interest formula:

  • frequency = 12 - Default to monthly compounding
  • principal * Math.pow(1 + rate / frequency, frequency * time) - Compound interest formula
    • rate / frequency - Interest rate per compounding period
    • 1 + rate / frequency - Growth factor per period
    • frequency * time - Total number of compounding periods
    • Math.pow(base, exponent) - Raises base to the power of exponent
  • interest: amount - principal - Calculate total interest earned
    loanPayment(principal, rate, payments) {
        const monthlyRate = rate / 12;
        const payment = principal * (monthlyRate * Math.pow(1 + monthlyRate, payments)) / 
                       (Math.pow(1 + monthlyRate, payments) - 1);

Loan payment calculation:

  • const monthlyRate = rate / 12 - Convert annual rate to monthly
  • Complex loan payment formula:
    • monthlyRate * Math.pow(1 + monthlyRate, payments) - Numerator
    • Math.pow(1 + monthlyRate, payments) - 1 - Denominator
    • This formula calculates fixed monthly payment for loan
        // Generate amortization schedule
        const schedule = [];
        let balance = principal;
        
        for (let i = 1; i <= payments; i++) {
            const interestPayment = balance * monthlyRate;
            const principalPayment = payment - interestPayment;
            balance -= principalPayment;
            
            schedule.push({
                payment: i,
                paymentAmount: payment,
                principal: principalPayment,
                interest: interestPayment,
                balance: Math.max(0, balance)
            });
        }

Amortization schedule generation:

  • const schedule = [] - Array to store payment breakdown
  • let balance = principal - Track remaining loan balance
  • for (let i = 1; i <= payments; i++) - Loop for each payment
  • const interestPayment = balance * monthlyRate - Interest portion of payment
  • const principalPayment = payment - interestPayment - Principal portion
  • balance -= principalPayment - Reduce remaining balance
  • Math.max(0, balance) - Ensure balance never goes below zero

๐Ÿ’ก Pro Tips for Array-Based Calculators

Performance Optimization

// Efficient array operations for large datasets
class OptimizedCalculator {
    // Use typed arrays for better performance with large numbers
    createTypedArray(size, type = 'Float64Array') {
        switch(type) {
            case 'Int32Array': return new Int32Array(size);
            case 'Float32Array': return new Float32Array(size);
            case 'Float64Array': return new Float64Array(size);
            default: return new Array(size);
        }
    }
    
    // Batch operations for better performance
    batchCalculate(numbers, operation) {
        const results = new Array(numbers.length);
        
        for (let i = 0; i < numbers.length; i++) {
            switch(operation) {
                case 'square': results[i] = numbers[i] * numbers[i]; break;
                case 'sqrt': results[i] = Math.sqrt(numbers[i]); break;
                case 'log': results[i] = Math.log(numbers[i]); break;
                default: results[i] = numbers[i];
            }
        }
        
        return results;
    }
}

๐Ÿ“– Line-by-Line Explanation: Performance Optimization

    createTypedArray(size, type = 'Float64Array') {
        switch(type) {
            case 'Int32Array': return new Int32Array(size);
            case 'Float32Array': return new Float32Array(size);
            case 'Float64Array': return new Float64Array(size);
            default: return new Array(size);
        }
    }

Typed arrays for performance:

  • createTypedArray(size, type = 'Float64Array') - Create optimized array
  • switch(type) - Choose array type based on data
  • new Int32Array(size) - Array for 32-bit integers (faster than regular arrays)
  • new Float32Array(size) - Array for 32-bit floating point numbers
  • new Float64Array(size) - Array for 64-bit floating point numbers
  • Typed arrays use less memory and are faster for numerical computations
    batchCalculate(numbers, operation) {
        const results = new Array(numbers.length);
        
        for (let i = 0; i < numbers.length; i++) {
            switch(operation) {
                case 'square': results[i] = numbers[i] * numbers[i]; break;
                case 'sqrt': results[i] = Math.sqrt(numbers[i]); break;
                case 'log': results[i] = Math.log(numbers[i]); break;
                default: results[i] = numbers[i];
            }
        }
        
        return results;
    }

Batch processing explanation:

  • const results = new Array(numbers.length) - Pre-allocate result array
    • Pre-allocation is faster than growing array dynamically
  • for (let i = 0; i < numbers.length; i++) - Process each number
  • case 'square': results[i] = numbers[i] * numbers[i] - Square operation
  • Math.sqrt(numbers[i]) - Square root operation
  • Math.log(numbers[i]) - Natural logarithm operation
  • Processing in batches is more efficient than individual operations

๐ŸŽฏ Your Array Calculator Mission

Build Your Ultimate Calculator!

Now itโ€™s your turn! Create a calculator that combines multiple array features:

  1. ๐Ÿ“ฑ Basic Calculator - Addition, subtraction, multiplication, division
  2. ๐Ÿ“œ History System - Store and recall calculations
  3. ๐Ÿ“Š Statistics Mode - Mean, median, mode calculations
  4. ๐Ÿ”ข Multi-Number Operations - Work with datasets
  5. ๐Ÿ’พ Memory Functions - Store and recall values
  6. ๐ŸŽฒ Random Generator - Generate number sets
  7. ๐Ÿ“ˆ Advanced Functions - Scientific or financial calculations

Starter Template:

class UltimateCalculator {
    constructor() {
        this.history = [];
        this.memory = [];
        this.currentDataset = [];
        // Add your properties here
    }
    
    // Implement your calculator methods here
    calculate(operation, ...args) {
        // Your calculation logic
    }
    
    // Add more methods for different features
}

๐Ÿ“– Starter Template Explanation:

class UltimateCalculator {
    constructor() {
        this.history = [];      // Array to store calculation history
        this.memory = [];       // Array for memory storage functions
        this.currentDataset = []; // Array for statistical operations
        // Add your properties here
    }

Template breakdown:

  • class UltimateCalculator - Create your custom calculator class
  • this.history = [] - Store all calculations for undo/redo functionality
  • this.memory = [] - Implement memory store/recall features
  • this.currentDataset = [] - Hold numbers for statistical calculations
    calculate(operation, ...args) {
        // Your calculation logic
    }
  • calculate(operation, ...args) - Main calculation method
  • ...args - Rest parameter to accept any number of arguments
  • This method should handle different types of operations

๐Ÿš€ Ready to Build?

Arrays transform simple calculators into powerful computational tools! With the techniques in this guide, you can create calculators that:

  • Remember everything with history arrays
  • Handle complex data with multi-dimensional arrays
  • Perform advanced statistics with data processing
  • Support scientific functions with mathematical arrays
  • Manage financial calculations with structured data

Your challenge: Pick one of the calculator examples and extend it with your own creative features!

Happy coding! ๐ŸŽ‰

๐Ÿ“‹ Cell 2 Table of Contents

๐Ÿ—‚๏ธ Complete Navigation Guide

### **๐Ÿ“š Quick Section Jump** | ๐ŸŽฏ **Main Topics** | ๐Ÿ“– **Educational Content** | ๐Ÿ’ป **Code Examples** | |-------------------|---------------------------|---------------------| | [๐Ÿš€ Why Arrays Make Calculators Amazing](#-why-arrays-make-calculators-amazing) | [๐Ÿ“– Basic Memory System Explanation](#-line-by-line-explanation-basic-memory-system) | [Example Usage](#example-usage) | | [๐ŸŽฏ Calculator Array Fundamentals](#-calculator-array-fundamentals) | [๐Ÿ“– Array Calculator Explanation](#-line-by-line-explanation-array-calculator) | [Usage Example](#usage-example) | | [๐Ÿงฎ Advanced Calculator Features](#-advanced-calculator-features-with-arrays) | [๐Ÿ“– Statistical Calculator Explanation](#-line-by-line-explanation-statistical-calculator) | [Statistics Example](#statistics-example) | | [๐Ÿ“Š Statistical Calculator Functions](#-statistical-calculator-functions) | [๐Ÿ“– History Calculator Explanation](#-line-by-line-explanation-history-calculator) | [Matrix Example](#matrix-example) | | [๐ŸŽฎ Interactive Calculator Features](#-interactive-calculator-features) | [๐Ÿ“– Matrix Calculator Explanation](#-line-by-line-explanation-matrix-calculator) | [Random Examples](#random-examples) | | [๐Ÿ”ฌ Matrix Calculator with Arrays](#-matrix-calculator-with-arrays) | [๐Ÿ“– Random Number Generator Explanation](#-line-by-line-explanation-random-number-generator) | [Scientific Examples](#scientific-examples) | | [๐ŸŽฒ Random Number Generator](#-random-number-generator-with-arrays) | [๐Ÿ“– Scientific Calculator Explanation](#-line-by-line-explanation-scientific-calculator) | [Financial Examples](#financial-examples) | | [๐Ÿ† Calculator Challenge Projects](#-calculator-challenge-projects) | [๐Ÿ“– Financial Calculator Explanation](#-line-by-line-explanation-financial-calculator) | [Optimization Examples](#optimization-examples) | | [๐Ÿ’ก Pro Tips for Array-Based Calculators](#-pro-tips-for-array-based-calculators) | [๐Ÿ“– Performance Optimization Explanation](#-line-by-line-explanation-performance-optimization) | [Mission Examples](#mission-examples) |

๐ŸŽฏ Detailed Section Breakdown

๐Ÿ”ฐ Foundation Level (Start Here)

  1. ๐Ÿ”ง Array Hack Challenge: Building Better Calculators
    • Welcome and introduction to array-powered calculators
  2. ๐Ÿš€ Why Arrays Make Calculators Amazing
    • โœ… History Tracking capabilities
    • โœ… Multi-Number Operations
    • โœ… Statistical Functions
    • โœ… Memory Functions
    • โœ… Advanced Operations
  3. ๐ŸŽฏ Calculator Array Fundamentals
    • Basic Calculator Memory System - Core array concepts
    • ๐Ÿ“– Line-by-Line Explanation: Basic Memory System - Detailed code breakdown
    • Example Usage - Practical implementation examples

๐Ÿ”ธ Intermediate Level

  1. ๐Ÿงฎ Advanced Calculator Features with Arrays
    • Multi-Number Operations - ArrayCalculator class implementation
    • ๐Ÿ“– Line-by-Line Explanation: Array Calculator - Comprehensive code analysis
    • Usage Example - Practical applications
  2. ๐Ÿ“Š Statistical Calculator Functions
    • Advanced Statistics with Arrays - Mean, median, mode calculations
    • ๐Ÿ“– Line-by-Line Explanation: Statistical Calculator - Detailed function breakdown
    • Statistics Example - Real-world statistical computing
  3. ๐ŸŽฎ Interactive Calculator Features
    • Calculator History with Undo/Redo - State management with arrays
    • ๐Ÿ“– Line-by-Line Explanation: History Calculator - Navigation system analysis

๐Ÿ”บ Advanced Level

  1. ๐Ÿ”ฌ Matrix Calculator with Arrays
    • 2D Arrays for Matrix Operations - Linear algebra implementation
    • ๐Ÿ“– Line-by-Line Explanation: Matrix Calculator - Matrix math breakdown
    • Matrix Example - Complex mathematical operations
  2. ๐ŸŽฒ Random Number Generator with Arrays
    • Advanced Random Functions - Probability and distribution systems
    • ๐Ÿ“– Line-by-Line Explanation: Random Number Generator - Algorithm analysis

๐Ÿ—๏ธ Project Challenges

  1. ๐Ÿ† Calculator Challenge Projects
    • Challenge 1: Scientific Calculator Array - Advanced mathematical functions
    • ๐Ÿ“– Line-by-Line Explanation: Scientific Calculator - Scientific computing breakdown
    • Challenge 2: Financial Calculator - Economic and financial calculations
    • ๐Ÿ“– Line-by-Line Explanation: Financial Calculator - Financial algorithm analysis

โšก Optimization & Best Practices

  1. ๐Ÿ’ก Pro Tips for Array-Based Calculators
    • Performance Optimization - Efficient array operations
    • ๐Ÿ“– Line-by-Line Explanation: Performance Optimization - Speed and memory improvements
  2. ๐ŸŽฏ Your Array Calculator Mission
    • Build Your Ultimate Calculator! - Final project guidelines
    • Starter Template - Foundation code structure
    • ๐Ÿ“– Starter Template Explanation - Template code analysis
  3. ๐Ÿš€ Ready to Build? - Launch your calculator project

๐ŸŽ“ Learning Progression Guide

๐Ÿ”ฐ Beginner ๐Ÿ”ธ Intermediate ๐Ÿ”บ Advanced
1. Why Arrays Amazing 1. Advanced Features 1. Matrix Calculator
2. Array Fundamentals 2. Statistical Functions 2. Random Generator
3. Basic Memory System 3. Interactive Features 3. Challenge Projects
4. Example Usage 4. Usage Examples 4. Performance Tips

๐ŸŽฏ Key Skills Youโ€™ll Master:

  • โœ… Array Fundamentals: push(), pop(), shift(), slice()
  • โœ… Object-Oriented Programming: Classes, methods, inheritance
  • โœ… State Management: History tracking, undo/redo systems
  • โœ… Mathematical Computing: Statistics, linear algebra, financial calculations
  • โœ… Performance Optimization: Efficient algorithms and memory management
  • โœ… Code Organization: Modular design and best practices

๐Ÿš€ Quick Start Navigation

Choose your learning path:



๐ŸŽฏ Integrating Arrays into Starter Calculator Template

Letโ€™s take the basic starter calculator and supercharge it with array functionality! Hereโ€™s how to transform the simple calculator into a powerful array-enhanced tool.

๐Ÿ”ง Enhanced Starter Calculator with Array Features

---
title: JS Array-Enhanced Calculator
comments: true
hide: true
layout: opencs
description: A starter calculator enhanced with powerful array functionality for history, memory, and advanced operations.
permalink: /array-calculator
---

<!-- Enhanced Calculator with Array Features -->
<style>
  .calculator-output {
    grid-column: span 4;
    grid-row: span 1;
    border-radius: 10px;
    padding: 0.25em;
    font-size: 20px;
    border: 5px solid black;
    display: flex;
    align-items: center;
    justify-content: flex-end; /* Right align result */
  }
  
  /* History display styling */
  .history-display {
    grid-column: span 4;
    max-height: 100px;
    overflow-y: auto;
    background: #f0f8ff;
    border: 2px solid #4682b4;
    border-radius: 8px;
    padding: 8px;
    font-size: 12px;
    margin-bottom: 10px;
  }
  
  /* Memory indicator */
  .memory-indicator {
    position: absolute;
    top: 5px;
    right: 5px;
    background: #32cd32;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    font-weight: bold;
  }
  
  canvas {
    filter: none;
  }
</style>

<!-- Add a container for the animation -->
<div id="animation">
  <div class="calculator-container" style="position: relative;">
      <!-- Memory indicator (hidden by default) -->
      <div class="memory-indicator" id="memoryIndicator" style="display: none;">M</div>
      
      <!-- History display -->
      <div class="history-display" id="historyDisplay">
        <strong>History:</strong><br>
        <span id="historyContent">No calculations yet</span>
      </div>
      
      <!-- Main display -->
      <div class="calculator-output" id="output">0</div>
      
      <!-- Calculator buttons -->
      <!--row 1-->
      <div class="calculator-number">1</div>
      <div class="calculator-number">2</div>
      <div class="calculator-number">3</div>
      <div class="calculator-operation">+</div>
      <!--row 2-->
      <div class="calculator-number">4</div>
      <div class="calculator-number">5</div>
      <div class="calculator-number">6</div>
      <div class="calculator-operation">-</div>
      <!--row 3-->
      <div class="calculator-number">7</div>
      <div class="calculator-number">8</div>
      <div class="calculator-number">9</div>
      <div class="calculator-operation">*</div>
      <!--row 4-->
      <div class="calculator-clear">A/C</div>
      <div class="calculator-number">0</div>
      <div class="calculator-number">.</div>
      <div class="calculator-operation">/</div>
      <!--row 5 - Array enhanced buttons-->
      <div class="calculator-operation" id="memStore">MS</div>  <!-- Memory Store -->
      <div class="calculator-operation" id="memRecall">MR</div> <!-- Memory Recall -->
      <div class="calculator-operation" id="memClear">MC</div>  <!-- Memory Clear -->
      <div class="calculator-equals">=</div>
  </div>
</div>

<!-- JavaScript with Array Integration -->
<script>
// ===== ARRAY-ENHANCED CALCULATOR =====
// Original calculator variables
var firstNumber = null;    // stores the first number in calculation
var operator = null;       // stores the current operator (+, -, *, /)
var nextReady = true;      // flag for new number input

// ===== ARRAY FUNCTIONALITY =====
// Array-based memory system
let calculatorMemory = [];     // array to store memory values
let calculationHistory = [];   // array to store calculation history
let currentNumbers = [];       // array for multi-number operations

// ===== DOM ELEMENTS =====
const output = document.getElementById("output");                    // calculator display
const numbers = document.querySelectorAll(".calculator-number");    // number buttons
const operations = document.querySelectorAll(".calculator-operation"); // operation buttons
const clear = document.querySelectorAll(".calculator-clear");       // clear button
const equals = document.querySelectorAll(".calculator-equals");     // equals button
const historyContent = document.getElementById("historyContent");   // history display
const memoryIndicator = document.getElementById("memoryIndicator"); // memory indicator

// ===== ARRAY-ENHANCED FUNCTIONS =====

// Store calculation in history array
function storeCalculation(operation, result) {
    // Create calculation object with operation details
    const calculation = {
        operation: operation,        // the math operation performed
        result: result,             // the calculated result
        timestamp: new Date().toLocaleString() // when calculation happened
    };
    
    // Add to history array using push()
    calculationHistory.push(calculation);
    
    // Keep only last 5 calculations to save space
    if (calculationHistory.length > 5) {
        calculationHistory.shift(); // remove first (oldest) element
    }
    
    // Update history display
    updateHistoryDisplay();
}

// Update the visual history display
function updateHistoryDisplay() {
    if (calculationHistory.length === 0) {
        historyContent.innerHTML = "No calculations yet";
        return;
    }
    
    // Build HTML string from history array
    let historyHTML = "";
    calculationHistory.forEach((calc, index) => {
        historyHTML += `${calc.operation} = ${calc.result}<br>`;
    });
    
    historyContent.innerHTML = historyHTML;
}

// Memory store function using arrays
function memoryStore(value) {
    calculatorMemory.push(value);           // add value to memory array
    console.log(`Stored: ${value}`);        // log confirmation
    memoryIndicator.style.display = "flex"; // show memory indicator
    
    // Keep only last 3 memory values
    if (calculatorMemory.length > 3) {
        calculatorMemory.shift(); // remove oldest memory
    }
}

// Memory recall function
function memoryRecall() {
    // Check if memory array has values
    if (calculatorMemory.length > 0) {
        // Return last stored value (most recent)
        return calculatorMemory[calculatorMemory.length - 1];
    }
    return 0; // return 0 if no memory
}

// Memory clear function
function memoryClear() {
    calculatorMemory = [];                   // empty the memory array
    memoryIndicator.style.display = "none"; // hide memory indicator
    console.log("Memory cleared!");
}

// ===== ENHANCED CALCULATOR FUNCTIONS =====

// Number button listeners (same as original)
numbers.forEach(button => {
    button.addEventListener("click", function() {
        number(button.textContent);
    });
});

// Enhanced number function with array logging
function number(value) {
    if (value != ".") {
        if (nextReady == true) {
            output.innerHTML = value;
            if (value != "0") {
                nextReady = false;
            }
        } else {
            output.innerHTML = output.innerHTML + value;
        }
    } else {
        // Decimal point handling
        if (output.innerHTML.indexOf(".") == -1) {
            output.innerHTML = output.innerHTML + value;
            nextReady = false;
        }
    }
}

// Operation button listeners (enhanced)
operations.forEach(button => {
    // Skip memory buttons - they have separate listeners
    if (!["MS", "MR", "MC"].includes(button.textContent)) {
        button.addEventListener("click", function() {
            operation(button.textContent);
        });
    }
});

// Enhanced operation function with history tracking
function operation(choice) {
    if (firstNumber == null) {
        firstNumber = parseInt(output.innerHTML);
        nextReady = true;
        operator = choice;
        return;
    }
    
    // Perform calculation and store in history
    const secondNumber = parseFloat(output.innerHTML);
    const result = calculate(firstNumber, secondNumber);
    
    // Store calculation in history array
    const operationString = `${firstNumber} ${operator} ${secondNumber}`;
    storeCalculation(operationString, result);
    
    firstNumber = result;
    operator = choice;
    output.innerHTML = firstNumber.toString();
    nextReady = true;
}

// Calculate function (same as original but with division added)
function calculate(first, second) {
    let result = 0;
    switch (operator) {
        case "+":
            result = first + second;
            break;
        case "-":
            result = first - second;
            break;
        case "*":
            result = first * second;
            break;
        case "/":
            result = second !== 0 ? first / second : "Error"; // Added division with zero check
            break;
        default: 
            break;
    }
    return result;
}

// Enhanced equals function with history
equals.forEach(button => {
    button.addEventListener("click", function() {
        equal();
    });
});

function equal() {
    if (firstNumber !== null && operator !== null) {
        const secondNumber = parseFloat(output.innerHTML);
        const result = calculate(firstNumber, secondNumber);
        
        // Store final calculation in history
        const operationString = `${firstNumber} ${operator} ${secondNumber}`;
        storeCalculation(operationString, result);
        
        output.innerHTML = result.toString();
        firstNumber = null;
        operator = null;
        nextReady = true;
    }
}

// Enhanced clear function
clear.forEach(button => {
    button.addEventListener("click", function() {
        clearCalc();
    });
});

function clearCalc() {
    firstNumber = null;
    operator = null;
    output.innerHTML = "0";
    nextReady = true;
    // Note: History and memory persist through clear
}

// ===== MEMORY BUTTON LISTENERS =====

// Memory Store button
document.getElementById("memStore").addEventListener("click", function() {
    const currentValue = parseFloat(output.innerHTML);
    memoryStore(currentValue);
});

// Memory Recall button  
document.getElementById("memRecall").addEventListener("click", function() {
    const recalledValue = memoryRecall();
    output.innerHTML = recalledValue.toString();
    nextReady = true;
});

// Memory Clear button
document.getElementById("memClear").addEventListener("click", function() {
    memoryClear();
});

// ===== ARRAY UTILITY FUNCTIONS =====

// Function to get full calculation history
function getCalculationHistory() {
    return calculationHistory; // return the entire history array
}

// Function to get memory contents
function getMemoryContents() {
    return calculatorMemory; // return the entire memory array
}

// Function to clear all history
function clearHistory() {
    calculationHistory = [];        // empty history array
    updateHistoryDisplay();         // refresh display
}

// ===== CONSOLE HELPERS FOR TESTING =====
// These functions can be called from browser console for testing

// Log current state
function logCalculatorState() {
    console.log("=== CALCULATOR STATE ===");
    console.log("Current Display:", output.innerHTML);
    console.log("First Number:", firstNumber);
    console.log("Operator:", operator);
    console.log("Next Ready:", nextReady);
    console.log("Memory Array:", calculatorMemory);
    console.log("History Array:", calculationHistory);
}

// Test memory functions
function testMemoryFunctions() {
    console.log("=== TESTING MEMORY ===");
    memoryStore(42);
    memoryStore(100);
    console.log("Memory after storing 42 and 100:", calculatorMemory);
    console.log("Memory recall:", memoryRecall());
    memoryClear();
    console.log("Memory after clear:", calculatorMemory);
}

// Test history functions  
function testHistoryFunctions() {
    console.log("=== TESTING HISTORY ===");
    storeCalculation("5 + 3", 8);
    storeCalculation("10 * 2", 20);
    storeCalculation("15 - 7", 8);
    console.log("History after adding calculations:", calculationHistory);
    console.log("Getting full history:", getCalculationHistory());
}

</script>

<!-- Vanta animations (same as original) -->
<script src="/team1-lessons/assets/js/three.r119.min.js"></script>
<script src="/team1-lessons/assets/js/vanta.halo.min.js"></script>
<script src="/team1-lessons/assets/js/vanta.birds.min.js"></script>
<script src="/team1-lessons/assets/js/vanta.net.min.js"></script>
<script src="/team1-lessons/assets/js/vanta.rings.min.js"></script>

<script>
// Vanta animation setup (same as original)
var vantaInstances = {
  halo: VANTA.HALO,
  birds: VANTA.BIRDS,
  net: VANTA.NET,
  rings: VANTA.RINGS
};

var vantaInstance = vantaInstances[Object.keys(vantaInstances)[Math.floor(Math.random() * Object.keys(vantaInstances).length)]];

vantaInstance({
  el: "#animation",
  mouseControls: true,
  touchControls: true,
  gyroControls: false
});
</script>

๐Ÿ” Key Array Enhancements Made:

  1. ๐Ÿ“œ History Array System:
    • calculationHistory[] - Stores all calculations with timestamps
    • storeCalculation() - Adds new calculations to history
    • updateHistoryDisplay() - Shows recent calculations on screen
  2. ๐Ÿ’พ Memory Array Functions:
    • calculatorMemory[] - Stores multiple memory values
    • memoryStore() - Adds values to memory using push()
    • memoryRecall() - Gets last stored value using array indexing
    • Visual memory indicator when values are stored
  3. ๐ŸŽฏ Enhanced User Interface:
    • History display panel showing recent calculations
    • Memory indicator (M) when values are stored
    • New memory buttons: MS (Store), MR (Recall), MC (Clear)
    • Division operator added to complete basic operations
  4. ๐Ÿ”ง Array Management:
    • Automatic history limiting (keeps last 5 calculations)
    • Memory limiting (keeps last 3 values)
    • Array manipulation using push(), shift(), and indexing
  5. ๐Ÿงช Testing Functions:
    • Console helper functions for debugging
    • State logging for development
    • Test functions for memory and history features

๐Ÿ’ก How Arrays Transform the Calculator:

Before (Basic): Simple calculator that forgets everything after each calculation

After (Array-Enhanced): Powerful calculator that:

  • โœ… Remembers calculation history
  • โœ… Stores multiple memory values
  • โœ… Provides visual feedback
  • โœ… Handles advanced operations
  • โœ… Offers debugging capabilities

This demonstrates how arrays can transform a basic calculator into a professional-grade computational tool! ๐Ÿš€