DEV Community

Cover image for Functional Programming in JavaScript: 10 Scenarios Demystified
MD. JAHID HOSSAIN
MD. JAHID HOSSAIN

Posted on • Updated on

Functional Programming in JavaScript: 10 Scenarios Demystified

Introduction:

Functional programming (FP) has become increasingly popular in JavaScript development for its ability to write cleaner, more maintainable and scalable code. However, understanding FP concepts and applying them in real-world scenarios can be daunting. In this comprehensive guide, we'll explore 10 real-life scenarios where functional programming shines in JavaScript. Each scenario will be accompanied by theoretical explanations, practical code examples and detailed explanations, providing you with the tools to master FP in your JavaScript projects.

1. Online Shopping Cart: Filtering Out Expired Items

Theory: Functional programming encourages using higher-order functions like filter for data manipulation tasks. In this scenario, we'll filter out expired items from an online shopping cart.

Explanation: We'll define a predicate function to determine if an item is expired and use the filter function to remove expired items from the cart.

Code:

const cart = [...]; // Array of items in the shopping cart

const isItemExpired = (item) => item.expiryDate < Date.now();

const updatedCart = cart.filter(item => !isItemExpired(item));
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a predicate function isItemExpired that checks if an item's expiry date is in the past.
  • We use the filter function to create a new array updatedCart containing only the items that are not expired.

2. Social Media Feed: Mapping Usernames to User Profiles

Theory: Functional programming promotes using map to transform data from one form to another. In this scenario, we'll map usernames to user profiles in a social media feed.

Explanation: We'll extract usernames from a list of posts and map them to corresponding user profiles fetched from a database.

Code:

const posts = [...]; // Array of social media posts
const userProfileDB = {...}; // Object containing user profiles indexed by username

const getUserProfile = (username) => userProfileDB[username];

const postsWithUserProfiles = posts.map(post => ({
  ...post,
  userProfile: getUserProfile(post.author)
}));
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a function getUserProfile to retrieve a user's profile from the database based on their username.
  • We use the map function to create a new array postsWithUserProfiles where each post is augmented with its author's user profile.

3. Task Management App: Reducing Pending Tasks

Theory: Functional programming promotes using reduce to perform operations on lists and accumulate results. In this scenario, we'll calculate the total number of pending tasks in a task management app.

Explanation: We'll use the reduce function to iterate over a list of tasks and count the number of pending tasks.

Code:

const tasks = [...]; // Array of task objects

const countPendingTasks = (acc, task) => task.status === 'pending' ? acc + 1 : acc;

const totalPendingTasks = tasks.reduce(countPendingTasks, 0);
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a reducer function countPendingTasks that increments the accumulator if a task's status is 'pending'.
  • We use the reduce function to iterate over the tasks array, applying the reducer function to calculate the total number of pending tasks.

4. Email Client: Composing Email Templates

Theory: Functional programming encourages composing functions to create more complex behaviors. In this scenario, we'll compose functions to generate email templates for different types of emails.

Explanation: We'll create reusable functions for generating different parts of an email template (e.g., subject, body) and compose them to generate complete email templates.

Code:

const createEmailSubject = (type) => `Regarding ${type}`;
const createEmailBody = (content) => `Dear user,\n\n${content}\n\nRegards,\nYour Email Client`;

const composeEmailTemplate = (type, content) => ({
  subject: createEmailSubject(type),
  body: createEmailBody(content)
});

const welcomeEmail = composeEmailTemplate('Welcome', 'Welcome to our platform!');
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define functions createEmailSubject and createEmailBody to generate the subject and body of an email, respectively.
  • We use the composeEmailTemplate function to compose the subject and body into a complete email template for a given type and content.

5. Fitness App: Calculating Calorie Burn

Theory: Functional programming promotes using recursion for repetitive tasks. In this scenario, we'll use recursion to calculate the total calorie burn for a workout routine.

Explanation: We'll define a recursive function to calculate the total calorie burn by summing the calorie burn for each exercise in the workout routine.

Code:

const calculateCalorieBurn = (exercises) => {
  if (exercises.length === 0) {
    return 0;
  } else {
    const [currentExercise, ...remainingExercises] = exercises;
    return currentExercise.caloriesBurned + calculateCalorieBurn(remainingExercises);
  }
};

const workoutRoutine = [...]; // Array of exercise objects
const totalCalorieBurn = calculateCalorieBurn(workoutRoutine);
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a recursive function calculateCalorieBurn that takes an array of exercises and calculates the total calorie burn by summing the calorie burn for each exercise.
  • The base case of the recursion is when there are no more exercises left, in which case the total calorie burn is 0.

6. Blogging Platform: Formatting Markdown Content

Theory: Functional programming promotes using pure functions for data transformation. In this scenario, we'll use pure functions to format Markdown content for display on a blogging platform.

Explanation: We'll define pure functions to convert Markdown content to HTML and add additional styling.

Code:

const convertMarkdownToHTML = (markdownContent) => {
  // Logic to convert Markdown to HTML
};

const addStylingToHTML = (htmlContent) => {
  // Logic to add styling to HTML
};

const markdownContent = '## Title\n\nThis is a **bold** text.';
const formattedHTML = addStylingToHTML(convertMarkdownToHTML(markdownContent));
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define two pure functions convertMarkdownToHTML and addStylingToHTML to convert Markdown content to HTML and add styling, respectively.
  • We chain the functions together to format the Markdown content and apply styling, resulting in formatted HTML for display.

7. Financial App: Calculating Compound Interest

Theory: Functional programming promotes using immutable data structures to avoid unintended side effects. In this scenario, we'll calculate compound interest using immutable data structures.

Explanation: We'll define a function to calculate compound interest without mutating the input variables.

Code:

const calculateCompoundInterest = (principal, rate, time) => {
  const amount = principal * Math.pow((1 + rate / 100), time);
  const interest = amount - principal;
  return { amount, interest };
};

const principal = 1000;
const rate = 5; // Annual interest rate in percentage
const time = 3; // Number of years
const compoundInterest = calculateCompoundInterest(principal, rate, time);
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a function calculateCompoundInterest that takes the principal amount, annual interest rate, and time period as input and returns the compound interest amount.
  • Inside the function, we calculate the compound interest amount using immutable calculations without mutating the input variables.
  • The result is returned as an object containing the total amount and the interest accrued.

8. E-commerce Platform: Sorting Products by Price

Theory: Functional programming promotes using higher-order functions for list processing tasks. In this scenario, we'll use the sort function to sort products by price.

Explanation: We'll define a comparator function to specify the sorting order and use the sort function to sort products by price.

Code:

const products = [...]; // Array of product objects

const sortByPrice = (a, b) => a.price - b.price;

const sortedProducts = products.sort(sortByPrice);
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a comparator function sortByPrice that compares two products based on their price.
  • We use the sort function to sort the array of products using the sortByPrice comparator function, resulting in a new array of products sorted by price.

9. Music Streaming App: Filtering Songs by Genre

Theory: Functional programming promotes using declarative code for readability. In this scenario, we'll use the filter function to filter songs by genre in a music streaming app.

Explanation: We'll define a predicate function to filter songs by genre and use the filter function to apply the filter.

Code:

const songs = [...]; // Array of song objects

const filterSongsByGenre = (genre) => (song) => song.genre === genre;

const genre = 'Rock';
const rockSongs = songs.filter(filterSongsByGenre(genre));
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a higher-order function filterSongsByGenre that takes a genre as input and returns a predicate function to filter songs by that genre.
  • We use the filter function to create a new array rockSongs containing only the songs that match the specified genre.

10. Weather App: Predicting Weather Trends

Theory: Functional programming promotes using recursion for repetitive tasks. In this scenario, we'll use recursion to predict weather trends based on historical data.

Explanation: We'll define a recursive function to analyze historical weather data and predict weather trends for the future.

Code:

const predictWeatherTrend = (historicalData) => {
  // Logic to analyze historical data and predict weather trend
};

const historicalWeatherData = [...]; // Array of historical weather data objects
const weatherTrend = predictWeatherTrend(historicalWeatherData);
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • We define a recursive function predictWeatherTrend that takes historical weather data as input and analyzes it to predict weather trends.
  • The function recursively analyzes historical data to identify patterns and predict future weather trends.

Conclusion

In conclusion, functional programming provides a powerful and intuitive approach to solving real-world problems in JavaScript. By emphasizing the use of higher-order functions like map, filter, sort and reduce, developers can efficiently manipulate data, streamline workflows, and create more maintainable code.

Through scenarios ranging from filtering online shopping carts to sorting restaurant reservations, we've seen how functional programming principles enhance code readability, promote modularity, and simplify complex tasks. Whether you're analyzing user interactions, prioritizing tasks, or formatting content, functional programming offers elegant solutions that make your code more concise and expressive.

By embracing functional programming in your JavaScript projects, you'll not only improve your coding skills but also unlock new possibilities for creating cleaner, more scalable, and more reliable applications. So, dive into functional programming, explore its features, and unleash the full potential of JavaScript in your development journey.

Top comments (0)