Higher-Order Functions - Exploring the Power of Higher-Order Functions in JavaScript
- The Traditional Approach: Normal Functions
Before we explore higher-order functions, let's take a look at the traditional approach to calculating the area, circumference, and diameter of an array of radius using normal functions.
const radius = [3, 1, 2, 4];
//Area
const calculateArea = function(radius){
const output = [];
for(let i = 0; i < radius.lenght; i++){
output.push( Math.PI * radius[i] * radius[i] )
}
return output;
}
console.log(calculateArea(radius));
// Circumference
const calculateCircumference = function(radius){
const output = [];
for(let i= 0; i < radius.length; i++){
output.push( 2 * Math.PI * radius[i] )
}
return output;
}
console.log(calculateCircumference(radius));
// Diameter
const calculateDiameter = function(radius){
const output = [];
for(let i= 0; i < radius.length; i++){
output.push( 2 * radius[i] )
}
return output;
}
console.log(calculateDiameter(radius));
This approach works, but it involves repetitive code for each calculation, making it less maintainable and harder to read.
- The Modern Approach: Higher-Order Functions
Now, let's explore a more elegant and efficient solution using higher-order functions in JavaScript.
const radius = [3, 1, 2, 4];
// Helper functions
const area = function(radius){
return Math.PI * radius * radius;
}
const circumference = function(radius){
return 2 * Math.PI * radius;
}
const diameter = function(radius){
return 2 * radius;
}
// Higher-order function
const calculate = function(radius, logic){
const output = [];
for(let i= 0; i < radius.length; i++){
output.push(logic(radius[i]))
}
return output;
}
console.log(calculate(radius, area));
console.log(calculate(radius, circumference));
console.log(calculate(radius, diameter));
In this modern approach, we define three helper functions for area, circumference, and diameter calculations. Then, we create a higher-order function called calculate, which takes an array of radius and a logic function as arguments. The calculate function iterates through the array of radius and applies the provided logic function to each element, resulting in a concise and reusable code.
Comments
Post a Comment