javascript
exercises
exercises.js⚡javascript
/**
* =====================================================
* 5.3 ARROW FUNCTIONS - EXERCISES
* =====================================================
* Practice arrow function syntax
*/
/**
* Exercise 1: Convert to Arrow Function
*
* Convert this function to an arrow function with implicit return.
* function double(x) { return x * 2; }
*/
// TODO: Create arrow function
const double = undefined;
// Test cases:
console.log('Exercise 1:');
// console.log(double(5)); // 10
// console.log(double(0)); // 0
// console.log(double(-3)); // -6
/**
* Exercise 2: No Parameters
*
* Create an arrow function that returns a random number between 0-100.
*/
const randomNumber = undefined;
// Test cases:
console.log('\nExercise 2:');
// console.log(randomNumber()); // Random 0-100
// console.log(randomNumber()); // Random 0-100
/**
* Exercise 3: Multiple Parameters
*
* Create an arrow function that calculates the hypotenuse
* of a right triangle given sides a and b.
* Formula: √(a² + b²)
*/
const hypotenuse = undefined;
// Test cases:
console.log('\nExercise 3:');
// console.log(hypotenuse(3, 4)); // 5
// console.log(hypotenuse(5, 12)); // 13
/**
* Exercise 4: Return an Object
*
* Create an arrow function that returns an object with
* the given name and age, plus an isAdult property.
*/
const makePerson = undefined;
// Test cases:
console.log('\nExercise 4:');
// console.log(makePerson("Alice", 25));
// { name: "Alice", age: 25, isAdult: true }
// console.log(makePerson("Bob", 16));
// { name: "Bob", age: 16, isAdult: false }
/**
* Exercise 5: Array Map
*
* Use an arrow function with map to square all numbers.
*/
const squareAll = undefined;
// Test cases:
console.log('\nExercise 5:');
// console.log(squareAll([1, 2, 3, 4])); // [1, 4, 9, 16]
// console.log(squareAll([5, 6])); // [25, 36]
/**
* Exercise 6: Array Filter
*
* Use an arrow function with filter to get only strings
* longer than 3 characters.
*/
const filterLongStrings = undefined;
// Test cases:
console.log('\nExercise 6:');
// console.log(filterLongStrings(["hi", "hello", "a", "world"]));
// ["hello", "world"]
/**
* Exercise 7: Array Reduce
*
* Use an arrow function with reduce to find the maximum number.
*/
const findMax = undefined;
// Test cases:
console.log('\nExercise 7:');
// console.log(findMax([3, 7, 2, 9, 5])); // 9
// console.log(findMax([-5, -2, -8])); // -2
/**
* Exercise 8: Curried Add
*
* Create a curried arrow function that adds two numbers.
* add(2)(3) should return 5
*/
const add = undefined;
// Test cases:
console.log('\nExercise 8:');
// console.log(add(2)(3)); // 5
// console.log(add(10)(20)); // 30
// const addFive = add(5);
// console.log(addFive(3)); // 8
/**
* Exercise 9: Sort by Property
*
* Create an arrow function that sorts an array of objects
* by a specified property.
*/
const sortBy = undefined;
// Test cases:
console.log('\nExercise 9:');
const people = [
{ name: 'Charlie', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 },
];
// console.log(sortBy(people, "age"));
// [{ name: "Alice", age: 25 }, ...]
// console.log(sortBy(people, "name"));
// [{ name: "Alice", ...}, { name: "Bob", ...}, ...]
/**
* Exercise 10: Chain Array Methods
*
* Use arrow functions to:
* 1. Filter numbers greater than 10
* 2. Double each number
* 3. Sum the results
*/
const processNumbers = undefined;
// Test cases:
console.log('\nExercise 10:');
// console.log(processNumbers([5, 15, 3, 20, 8, 12]));
// (15*2 + 20*2 + 12*2) = 94
// =====================================================
// INTERMEDIATE EXERCISES
// =====================================================
/**
* Exercise 11: Compose Functions
*
* Create a compose function using arrow functions.
* compose(f, g)(x) = f(g(x))
*/
const compose = undefined;
// Test cases:
console.log('\nExercise 11:');
// const addOne = x => x + 1;
// const double = x => x * 2;
// const addOneThenDouble = compose(double, addOne);
// console.log(addOneThenDouble(5)); // 12
/**
* Exercise 12: Pipe Functions
*
* Create a pipe function (left-to-right composition).
* pipe(f, g, h)(x) = h(g(f(x)))
*/
const pipe = undefined;
// Test cases:
console.log('\nExercise 12:');
// const addTwo = x => x + 2;
// const triple = x => x * 3;
// const square = x => x * x;
// const process = pipe(addTwo, triple, square);
// console.log(process(2)); // ((2+2)*3)² = 144
/**
* Exercise 13: Group By
*
* Create a groupBy function using arrow functions.
*/
const groupBy = undefined;
// Test cases:
console.log('\nExercise 13:');
// const items = [
// { type: "fruit", name: "apple" },
// { type: "vegetable", name: "carrot" },
// { type: "fruit", name: "banana" }
// ];
// console.log(groupBy(items, "type"));
// { fruit: [...], vegetable: [...] }
/**
* Exercise 14: Debounce
*
* Create a debounce function using arrow functions.
*/
const debounce = undefined;
// Test cases:
console.log('\nExercise 14:');
// const log = debounce(msg => console.log(msg), 100);
// log("a"); log("b"); log("c");
// // Only "c" should log after 100ms
/**
* Exercise 15: Partial Application
*
* Create a partial application function using arrow functions.
*/
const partial = undefined;
// Test cases:
console.log('\nExercise 15:');
// const greet = (greeting, name) => `${greeting}, ${name}!`;
// const sayHello = partial(greet, "Hello");
// console.log(sayHello("World")); // "Hello, World!"
// =====================================================
// BONUS CHALLENGES
// =====================================================
/**
* Bonus 1: Memoize with Arrow Functions
*
* Create a memoization function using arrow functions.
*/
const memoize = undefined;
/**
* Bonus 2: Throttle
*
* Create a throttle function using arrow functions.
* Limits function calls to once per interval.
*/
const throttle = undefined;
/**
* Bonus 3: Flatten Array
*
* Create a function to flatten nested arrays using arrow functions.
*/
const flatten = undefined;
// Test cases:
console.log('\nBonus 3:');
// console.log(flatten([1, [2, 3], [4, [5, 6]]]));
// [1, 2, 3, 4, 5, 6]
// =====================================================
// SOLUTIONS (Uncomment to check your answers)
// =====================================================
/*
// Exercise 1 Solution:
const double = x => x * 2;
// Exercise 2 Solution:
const randomNumber = () => Math.floor(Math.random() * 101);
// Exercise 3 Solution:
const hypotenuse = (a, b) => Math.sqrt(a * a + b * b);
// Exercise 4 Solution:
const makePerson = (name, age) => ({
name,
age,
isAdult: age >= 18
});
// Exercise 5 Solution:
const squareAll = arr => arr.map(n => n * n);
// Exercise 6 Solution:
const filterLongStrings = arr => arr.filter(s => s.length > 3);
// Exercise 7 Solution:
const findMax = arr => arr.reduce((max, n) => n > max ? n : max, arr[0]);
// Exercise 8 Solution:
const add = a => b => a + b;
// Exercise 9 Solution:
const sortBy = (arr, prop) => [...arr].sort((a, b) => {
if (a[prop] < b[prop]) return -1;
if (a[prop] > b[prop]) return 1;
return 0;
});
// Exercise 10 Solution:
const processNumbers = arr => arr
.filter(n => n > 10)
.map(n => n * 2)
.reduce((sum, n) => sum + n, 0);
// Exercise 11 Solution:
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
// Exercise 12 Solution:
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);
// Exercise 13 Solution:
const groupBy = (arr, prop) => arr.reduce((groups, item) => {
const key = item[prop];
groups[key] = groups[key] || [];
groups[key].push(item);
return groups;
}, {});
// Exercise 14 Solution:
const debounce = (fn, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
};
// Exercise 15 Solution:
const partial = (fn, ...presetArgs) => (...laterArgs) =>
fn(...presetArgs, ...laterArgs);
// Bonus 1 Solution:
const memoize = fn => {
const cache = new Map();
return (...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 2 Solution:
const throttle = (fn, interval) => {
let lastTime = 0;
return (...args) => {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn(...args);
}
};
};
// Bonus 3 Solution:
const flatten = arr => arr.reduce(
(flat, item) => flat.concat(Array.isArray(item) ? flatten(item) : item),
[]
);
*/