javascript

exercises

exercises.js
/**
 * =====================================================
 * 5.1 FUNCTION DECLARATIONS - EXERCISES
 * =====================================================
 * Practice writing function declarations
 */

/**
 * Exercise 1: Simple Greeting
 *
 * Create a function that returns a greeting message.
 * If no name is provided, use "World".
 */
function greet(name) {
  // TODO: Return "Hello, {name}!"
}

// Test cases:
console.log('Exercise 1:');
console.log(greet('Alice')); // "Hello, Alice!"
console.log(greet()); // "Hello, World!"

/**
 * Exercise 2: Calculate Circle Area
 *
 * Create a function that calculates the area of a circle.
 * Formula: π * r²
 */
function calculateCircleArea(radius) {
  // TODO: Return the area of a circle
}

// Test cases:
console.log('\nExercise 2:');
console.log(calculateCircleArea(5)); // ~78.54
console.log(calculateCircleArea(10)); // ~314.16

/**
 * Exercise 3: Temperature Converter
 *
 * Create a function that converts Celsius to Fahrenheit.
 * Formula: (C × 9/5) + 32
 */
function celsiusToFahrenheit(celsius) {
  // TODO: Convert and return Fahrenheit
}

// Test cases:
console.log('\nExercise 3:');
console.log(celsiusToFahrenheit(0)); // 32
console.log(celsiusToFahrenheit(100)); // 212
console.log(celsiusToFahrenheit(37)); // 98.6

/**
 * Exercise 4: Find Maximum
 *
 * Create a function that finds the maximum of three numbers.
 */
function findMax(a, b, c) {
  // TODO: Return the largest number
}

// Test cases:
console.log('\nExercise 4:');
console.log(findMax(1, 2, 3)); // 3
console.log(findMax(5, 2, 8)); // 8
console.log(findMax(-1, -5, -2)); // -1

/**
 * Exercise 5: Is Even
 *
 * Create a function that returns true if a number is even.
 */
function isEven(number) {
  // TODO: Return true if even, false if odd
}

// Test cases:
console.log('\nExercise 5:');
console.log(isEven(4)); // true
console.log(isEven(7)); // false
console.log(isEven(0)); // true

/**
 * Exercise 6: Count Vowels
 *
 * Create a function that counts vowels in a string.
 * Consider a, e, i, o, u as vowels (case insensitive).
 */
function countVowels(str) {
  // TODO: Return the count of vowels
}

// Test cases:
console.log('\nExercise 6:');
console.log(countVowels('hello')); // 2
console.log(countVowels('AEIOU')); // 5
console.log(countVowels('rhythm')); // 0

/**
 * Exercise 7: Sum of Array
 *
 * Create a function that sums all numbers in an array.
 * Use rest parameters to accept any number of arguments.
 */
function sumAll(...numbers) {
  // TODO: Return the sum of all numbers
}

// Test cases:
console.log('\nExercise 7:');
console.log(sumAll(1, 2, 3)); // 6
console.log(sumAll(10, 20, 30, 40)); // 100
console.log(sumAll()); // 0

/**
 * Exercise 8: Factorial
 *
 * Create a function that calculates the factorial of a number.
 * n! = n × (n-1) × (n-2) × ... × 1
 * 0! = 1
 */
function factorial(n) {
  // TODO: Calculate factorial
}

// Test cases:
console.log('\nExercise 8:');
console.log(factorial(5)); // 120
console.log(factorial(0)); // 1
console.log(factorial(3)); // 6

/**
 * Exercise 9: Reverse String
 *
 * Create a function that reverses a string.
 */
function reverseString(str) {
  // TODO: Return the reversed string
}

// Test cases:
console.log('\nExercise 9:');
console.log(reverseString('hello')); // "olleh"
console.log(reverseString('JavaScript')); // "tpircSavaJ"

/**
 * Exercise 10: Create Person
 *
 * Create a function that returns a person object.
 * Use default values for optional properties.
 */
function createPerson(name, age, city = 'Unknown') {
  // TODO: Return a person object with name, age, city, and isAdult (age >= 18)
}

// Test cases:
console.log('\nExercise 10:');
console.log(createPerson('Alice', 25, 'NYC'));
// { name: "Alice", age: 25, city: "NYC", isAdult: true }
console.log(createPerson('Bob', 16));
// { name: "Bob", age: 16, city: "Unknown", isAdult: false }

// =====================================================
// INTERMEDIATE EXERCISES
// =====================================================

/**
 * Exercise 11: FizzBuzz
 *
 * Create a function that returns:
 * - "FizzBuzz" if n is divisible by both 3 and 5
 * - "Fizz" if n is divisible by 3
 * - "Buzz" if n is divisible by 5
 * - The number as string otherwise
 */
function fizzBuzz(n) {
  // TODO: Implement FizzBuzz logic
}

// Test cases:
console.log('\nExercise 11:');
console.log(fizzBuzz(15)); // "FizzBuzz"
console.log(fizzBuzz(9)); // "Fizz"
console.log(fizzBuzz(10)); // "Buzz"
console.log(fizzBuzz(7)); // "7"

/**
 * Exercise 12: Calculate Average
 *
 * Create a function that calculates the average of an array of numbers.
 * Return 0 for empty arrays.
 */
function calculateAverage(numbers) {
  // TODO: Calculate and return average
}

// Test cases:
console.log('\nExercise 12:');
console.log(calculateAverage([1, 2, 3, 4, 5])); // 3
console.log(calculateAverage([10, 20])); // 15
console.log(calculateAverage([])); // 0

/**
 * Exercise 13: Validate Password
 *
 * Create a function that validates a password:
 * - At least 8 characters
 * - Contains at least one number
 * - Contains at least one uppercase letter
 * Return an object with { valid: boolean, errors: string[] }
 */
function validatePassword(password) {
  // TODO: Validate password and return result
}

// Test cases:
console.log('\nExercise 13:');
console.log(validatePassword('Password1')); // { valid: true, errors: [] }
console.log(validatePassword('pass')); // { valid: false, errors: [...] }

/**
 * Exercise 14: Create Counter
 *
 * Create a function that returns a counter function.
 * The returned function should return an incrementing number each call.
 */
function createCounter(start = 0) {
  // TODO: Return a function that returns incrementing numbers
}

// Test cases:
console.log('\nExercise 14:');
const counter1 = createCounter();
console.log(counter1()); // 1
console.log(counter1()); // 2
console.log(counter1()); // 3

const counter2 = createCounter(10);
console.log(counter2()); // 11
console.log(counter2()); // 12

/**
 * Exercise 15: Calculate Statistics
 *
 * Create a function that returns statistics about an array of numbers:
 * min, max, sum, count, average
 */
function getStatistics(numbers) {
  // TODO: Return an object with statistics
}

// Test cases:
console.log('\nExercise 15:');
console.log(getStatistics([1, 2, 3, 4, 5]));
// { min: 1, max: 5, sum: 15, count: 5, average: 3 }

// =====================================================
// BONUS CHALLENGES
// =====================================================

/**
 * Bonus 1: Compose Functions
 *
 * Create a function that takes multiple functions and returns
 * a new function that applies them right-to-left.
 * compose(f, g, h)(x) === f(g(h(x)))
 */
function compose(...fns) {
  // TODO: Implement function composition
}

console.log('\nBonus 1:');
const addOne = (x) => x + 1;
const double = (x) => x * 2;
const square = (x) => x * x;

const composed = compose(addOne, double, square);
// console.log(composed(3));  // 19 (3² = 9, 9*2 = 18, 18+1 = 19)

/**
 * Bonus 2: Memoize
 *
 * Create a function that memoizes (caches) results of another function.
 */
function memoize(fn) {
  // TODO: Implement memoization
}

/**
 * Bonus 3: Curry
 *
 * Create a curried version of a function with fixed arity.
 * curry(f)(a)(b)(c) === f(a, b, c)
 */
function curry(fn) {
  // TODO: Implement currying
}

// =====================================================
// SOLUTIONS (Uncomment to check your answers)
// =====================================================

/*
// Exercise 1 Solution:
function greet(name = "World") {
    return `Hello, ${name}!`;
}

// Exercise 2 Solution:
function calculateCircleArea(radius) {
    return Math.PI * radius * radius;
}

// Exercise 3 Solution:
function celsiusToFahrenheit(celsius) {
    return (celsius * 9/5) + 32;
}

// Exercise 4 Solution:
function findMax(a, b, c) {
    return Math.max(a, b, c);
}

// Exercise 5 Solution:
function isEven(number) {
    return number % 2 === 0;
}

// Exercise 6 Solution:
function countVowels(str) {
    const vowels = "aeiouAEIOU";
    let count = 0;
    for (const char of str) {
        if (vowels.includes(char)) {
            count++;
        }
    }
    return count;
}

// Exercise 7 Solution:
function sumAll(...numbers) {
    let total = 0;
    for (const num of numbers) {
        total += num;
    }
    return total;
}

// Exercise 8 Solution:
function factorial(n) {
    if (n <= 1) return 1;
    let result = 1;
    for (let i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

// Exercise 9 Solution:
function reverseString(str) {
    return str.split("").reverse().join("");
}

// Exercise 10 Solution:
function createPerson(name, age, city = "Unknown") {
    return {
        name,
        age,
        city,
        isAdult: age >= 18
    };
}

// Exercise 11 Solution:
function fizzBuzz(n) {
    if (n % 15 === 0) return "FizzBuzz";
    if (n % 3 === 0) return "Fizz";
    if (n % 5 === 0) return "Buzz";
    return String(n);
}

// Exercise 12 Solution:
function calculateAverage(numbers) {
    if (numbers.length === 0) return 0;
    const sum = numbers.reduce((a, b) => a + b, 0);
    return sum / numbers.length;
}

// Exercise 13 Solution:
function validatePassword(password) {
    const errors = [];
    if (password.length < 8) {
        errors.push("Password must be at least 8 characters");
    }
    if (!/\d/.test(password)) {
        errors.push("Password must contain a number");
    }
    if (!/[A-Z]/.test(password)) {
        errors.push("Password must contain an uppercase letter");
    }
    return { valid: errors.length === 0, errors };
}

// Exercise 14 Solution:
function createCounter(start = 0) {
    let count = start;
    return function() {
        count++;
        return count;
    };
}

// Exercise 15 Solution:
function getStatistics(numbers) {
    if (numbers.length === 0) {
        return { min: null, max: null, sum: 0, count: 0, average: null };
    }
    const sum = numbers.reduce((a, b) => a + b, 0);
    return {
        min: Math.min(...numbers),
        max: Math.max(...numbers),
        sum,
        count: numbers.length,
        average: sum / numbers.length
    };
}

// Bonus 1 Solution:
function compose(...fns) {
    return function(x) {
        return fns.reduceRight((acc, fn) => fn(acc), x);
    };
}

// Bonus 2 Solution:
function memoize(fn) {
    const cache = new Map();
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) {
            return cache.get(key);
        }
        const result = fn(...args);
        cache.set(key, result);
        return result;
    };
}

// Bonus 3 Solution:
function curry(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn(...args);
        }
        return function(...nextArgs) {
            return curried(...args, ...nextArgs);
        };
    };
}
*/
Exercises - JavaScript Tutorial | DeepML