Create a function that takes another function as an argument and calls it after 3 seconds (HOF + Callback).
Explanation: A higher-order function (HOF) is a function that takes another function as an argument or returns a function. Here, we use setTimeout to delay the execution of the callback function by 3 seconds.
// Higher-order function that accepts a callback
function delayedExecution(callback) {
setTimeout(callback, 3000); // Call the function after 3 seconds
}
// Callback function
function greet() {
console.log("Hello after 3 seconds!");
}
// Passing the callback function
delayedExecution(greet);
Implement your own version of .map() as a higher-order function.
Explanation: The map() method is a built-in JavaScript function that transforms each element of an array using a provided callback function and returns a new array. Here, we manually implement a custom myMap function.
// Custom implementation of map()
function myMap(array, callback) {
let result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array)); // Apply callback and push result
}
return result;
}
// Example usage
let numbers = [1, 2, 3, 4];
let squaredNumbers = myMap(numbers, num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16]
Write a function that uses closures to create a counter.
Explanation: Closures allow a function to maintain access to its lexical scope even after execution. Here, the counter function returns another function that increments and returns a count, preserving state across calls.
// Function that creates a counter using closure
function createCounter() {
let count = 0; // Private variable
return function() {
count++; // Increment count
return count;
};
}
// Example usage
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Implement a function that limits how many times another function can be called (Closure + HOF).
Explanation: This function allows another function to be called a specified number of times before becoming inactive. We use a closure to keep track of the remaining calls.
// Function to limit calls
function limitFunction(fn, limit) {
let count = 0; // Track calls
return function(...args) {
if (count < limit) {
count++;
return fn(...args);
} else {
console.log("Function call limit reached.");
}
};
}
// Example usage
function sayHello() {
console.log("Hello!");
}
const limitedHello = limitFunction(sayHello, 3);
limitedHello(); // Hello!
limitedHello(); // Hello!
limitedHello(); // Hello!
limitedHello(); // Function call limit reached.