Ways to combine and run the outcomes of several functions with Lodash

Imagine you have two distinct functions (or more) that take one argument from an executor and return the result object. Let's illustrate this with an example:

const style_1 = theme => ({
  header : {
      color : theme.primary
    }
})

const style_2 = theme => ({
  header : {
      backgroundColor : theme.secondary,
      color : "red"
    }
})

You want to execute these functions and merge the resulting objects into one! When dealing with objects, it's a simple task as shown below:

const style_1 = {
  header : {
      color : theme.primary
    }
}

const style_2 = {
  header : {
      backgroundColor : theme.secondary,
      color : "red"
    }
}

 const res = {...style_1, ...style_2}

The expected result is:

 { 
   header :
     { 
       backgroundColor : "black",
       color : "red"
      }
}

However, when working with functions, things can get a bit tricky.

So the question arises: Is it possible to implement what I want? (using Lodash or any other method)

I thought of creating something like this:

const style_1 = theme => ({
    header : {
        color : theme.secondary
        backgroundColor : "black"
    },
    footer : {
        color : "purple"
    }
})

const style_2 = (theme, extendStyles) => {
    const extendStyles = extendStyles(theme);

    return {
        header : {
            color : theme.primary,
            ...extendsStyles.header
        },
        ...extendStyles
    }
}

However, this solution seems a bit cumbersome as I need to manage this in every style that could potentially be overridden. Are there any utilities/helpers that can make this process smoother?

P.S. I'm exploring this "withStyle" feature of MaterialUI and trying to figure out the best approach to handle it.

Thank you for any assistance.

Answer №1

If you want to create a combined styled object from an array of style functions and a theme, you can utilize _.invokeMap() and _.merge():

You can achieve this by using the following code snippet:

const applyTheme = (styles, theme) =>
  _.merge(..._.invokeMap(styles, _.call, null, theme));

const style_1 = theme => ({
  header : {
      color : theme.primary,
      border: `1px solid ${theme.primary}`
    }
})

const style_2 = theme => ({
  header : {
      backgroundColor : theme.secondary,
      color : "red"
    }
})

const theme = { primary: 'red', secondary: 'blue' }

const result = applyTheme([style_1, style_2], theme)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The system cannot locate the module: Unable to find '@reactchartjs/react-chart-2.js'

I've been working on implementing this chart using the npm module called react-chartjs-2. I followed these steps to install the module: Ran the command: npm install --save react-chartjs-2 chart.js As a result, my package.json file now looks like th ...

How can I pass an Objective-C object to JavaScript?

Currently, I am working on a UIWebView project that involves HTML and JavaScript. One of my friends is working on something similar but for Android. The challenge I'm facing is that in Android, there is a simple way to send an Android object to JavaS ...

I am interested in altering the color of table rows using either JQuery or CSS

Looking to update row colors based on grouping. For example: Color the TR accordingly for every 5 rows: First 5 rows in green (0-4 Rows), Next five rows in red (5-9 Rows), Following five rows in yellow (10-14 Rows) and repeat the pattern... ...

What is the best way to adjust a div's height to fill the remaining space of the viewport after the header's height

Is there a way to create a hero section that fills 100vh minus the height of the header, especially when the height of the header is not fixed? I initially used CSS with a height property set to calc(100vh - 310px), where 310px represents the height of t ...

Transforming the primary image to the thumbnail image when hovering over it with JSON objects

Currently, I am facing an issue with my single-page web application project that involves using jQuery, JSON Bootstrap. So far, I have successfully created a category page, product selection page, and item page. The problem arises on the item page where ...

Tips for validating a dynamically created form with Bootstrap tabs using jQuery

For my project, I am dynamically creating an HTML form using jQuery. The page consists of five tabs, each with separate previous and next buttons. These tabs are designed using Bootstrap. Can someone please suggest the easiest way to validate this page? Fo ...

Is it possible to call a Node.js function from JavaScript using a <script> tag in a Jade template?

I have been working on developing a blog using Node.js, Express, and MongoDB. In the template for creating a new post, there are fields for both a title and a slug. To generate slugs, I am utilizing the Slugs for Node.js library from NPM: https://npmjs.or ...

Adding a background image to a box in MUI is a simple task that can enhance

I've been attempting to include a background image in the Box component of mui, but I can't seem to get it to work. Here is the code I've been using: const Main = () => { return ( <Box sx={{backgroundImage:'images/cove ...

Tips for expanding an input to fit the width of a div without altering the dimensions of a preceding span element

Let me explain, I have a form that includes a span and an input: <form onSubmit={e => handleSubmit(e)}> <Box className='form_box'> <span> <a href="/cd ...

Leveraging JavaScript to trigger onClick() functions for multiple buttons throughout a webpage

        While searching for solutions, I came across several articles with similar topics, but unfortunately, none of the proposed solutions worked. Please forgive me if it was due to my own error. Background I am assisting a client who is transition ...

Exploring MaterialUI v5: Customizing the appearance of Autocomplete selections

My task involves implementing basic styles to the options within the Autocomplete component of MUI v5. Specifically, I am aiming to modify the background color on hover and based on selection status. I have attempted two different approaches following the ...

User currently signed in: What specific information should be transmitted to the web browser?

Experience: Currently utilizing the MEAN stack for a web application and still in the learning process. The Concern: I am facing some confusion regarding a particular aspect. For instance, if a user is logged in (using Passport.js), I can access their inf ...

Navigating within a class-based component using Next.js: A brief guide

Is it possible to create a redirect from within an onSubmit call while maintaining CampaignNew as a class-based component? I have provided the code snippet below, and I am looking for guidance on achieving this. import React, { Component } from "rea ...

Fundamentals of Angular 2

It's not just an inconvenience, but something that truly frustrates me. Could someone please clarify the following: Why does Angular load these scripts in HTML directly from node_modules https://i.sstatic.net/D8UrG.png Why am I unable to simply imp ...

What is preventing d3.json from including cookies in the request?

I'm delving into the world of ajax requests with d3.js (v5) and I'm facing a little hiccup. Here's my code snippet: d3.json(uri).then(data =>console.log(data)); When I tried this in an app utilizing cookie authentication, I consistently ...

Access User Information from Facebook using Nativescript {N} oAuth Plugin

Developing an Android App with NativeScript I am in the process of creating an Android app using JavaScript and NativeScript. The initial page asks users to connect with Facebook, and my goal is to verify if an account exists with their email address. To ...

Eliminate web address parameter using regular expressions

Looking to remove a specific URL parameter from a given URL. For instance, if the URL is: http://example.com?foo=bar&baz=boo And I want to eliminate foo=bar to get: http://example.com?baz=boo Or removing baz=boo would leave me with: http://exampl ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

Is it possible to capture and store server responses on the client side using Node.js and React Native?

Here's a POST request I have: router.post("/projects", async (req, res) => { const { projectName, projectDescription, projectBudget, projectDuration, industry, companyName, numberOfEmployees, diamond, } = req.bod ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...