?? Elevating JavaScript Skills with Higher-Order Functions! ??
JavaScript Developer WorldWide
Join the JavaScript Developers worldwide JavaScript Developers JavaScript Coders JavaScript Freelancers
Exercise 1: Map Function
Problem: Use the map function to double each element of an array [1, 2, 3, 4].
Explanation: Demonstrates how to use the map higher-order function to apply a transformation to each element of an array.
Code:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map (num => num * 2);
console.log(doubled); // Outputs: [2, 4, 6, 8]
Exercise 2: Filter Function
Problem: Use the filter function to extract even numbers from an array [1, 2, 3, 4, 5].
Explanation: Illustrates how to use the filter higher-order function to select elements that satisfy a certain condition.
Code:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Outputs: [2, 4]
Exercise 3: Reduce Function
Problem: Use the reduce function to calculate the sum of an array [1, 2, 3, 4, 5].
Explanation: Shows how to use the reduce higher-order function to aggregate values into a single result.
Code:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Outputs: 15
Exercise 4: Chaining Higher-Order Functions
Problem: Given an array of numbers, filter out the even numbers, double the remaining ones, and then calculate their sum.
Explanation: Demonstrates the power of chaining multiple higher-order functions together for complex data transformations.
Code:
const numbers = [1, 2, 3, 4, 5];
const result = numbers
?.filter(num => num % 2 === 0)
?.map(num => num * 2)
?.reduce((acc, curr) => acc + curr, 0);
console.log(result); // Outputs: 12 (2*2 + 4*2)
Exercise 5: Using Higher-Order Functions with Objects
Problem: Given an array of objects representing people, extract just their names.
Explanation: Shows how to apply higher-order functions to extract specific properties from an array of objects.
Code:
const people = [
?{ name: "Alice", age: 30 },
?{ name: "Bob", age: 25 },
?{ name: "Charlie", age: 35 }
];
const names = people.map (person => person.name );
console.log(names); // Outputs: ["Alice", "Bob", "Charlie"]
Exercise 6: Composing Functions
Problem: Write a function compose that takes two functions as arguments and returns a new function that applies them sequentially.
Explanation: Introduces function composition, a technique to combine multiple functions into a single function.
Code:
const compose = (f, g) => (...args) => f(g(...args));
const add1 = x => x + 1;
领英推荐
const double = x => x * 2;
const add1ThenDouble = compose(double, add1);
console.log(add1ThenDouble(3)); // Outputs: 8 (3 + 1 = 4, 4 * 2 = 8)
Exercise 7: Currying Functions
Problem: Write a curried function add that takes two arguments and returns their sum.
Explanation: Introduces function currying, a technique to convert a function with multiple arguments into a sequence of functions, each taking a single argument.
Code:
const add = x => y => x + y;
const add5 = add(5);
console.log(add5(3)); // Outputs: 8 (5 + 3)
Exercise 8: Higher-Order Functions with Default Parameters
Problem: Write a function calculate that takes a binary operation function and two operands, with the second operand defaulting to 1.
Explanation: Illustrates how to use higher-order functions with default parameters to create flexible and reusable function compositions.
Code:
const calculate = (operation, x, y = 1) => operation(x, y);
const multiply = (x, y) => x * y;
console.log(calculate(multiply, 3)); // Outputs: 3 (3 * 1)
console.log(calculate(multiply, 3, 4)); // Outputs: 12 (3 * 4)
Exercise 9: Higher-Order Functions for Asynchronous Operations
Problem: Write a function fetchAndProcess that fetches data from an API endpoint and then processes it with a provided callback function.
Explanation: Demonstrates how to use higher-order functions to handle asynchronous operations and callbacks.
Code:
const fetchAndProcess = (url, callback) => {
?fetch(url)
?.then(response => response.json())
?.then(data => callback(data))
?.catch(error => console.error('Error:', error));
};
fetchAndProcess('https://jsonplaceholder.typicode.com/posts/1 ', console.log);
Exercise 10: Memoization with Higher-Order Functions
Problem: Write a function memoize that takes a pure function as input and returns a memoized version of that function.
Explanation: Explores memoization, a technique to cache the results of expensive function calls for better performance.
Code:
const memoize = (func) => {
?const cache = {};
?return (...args) => {
?const key = JSON.stringify(args);
?if (!(key in cache)) {
?cache[key] = func(...args);
?}
?return cache[key];
?};
};
const factorial = memoize(n => {
?if (n === 0) return 1;
?return n * factorial(n - 1);
});
console.log(factorial(5)); // Outputs: 120 (5!)
console.log(factorial(5)); // Outputs: 120 (cached result)