如何使用Lodash执行和合并多个函数结果

时间:2018-05-24 09:16:01

标签: javascript lodash material-ui jss

假设我们有两个不同的函数(或更多)接受来自某个执行器的一个参数并返回结果对象。让我举一个例子:

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

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

我想执行它们并将结果对象合并为一个!在对象的情况下,这是一项微不足道的任务,例如。

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

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

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

预期结果是

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

但是在功能方面它会变得有点烦人。

所以问题是。有可能实现我想要的吗? (通过Lodash或使用其他东西)

我已经决定要创建类似的东西

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
    }
}

但是这个解决方案有点丑陋,因为我应该在每种可能被覆盖的风格中照顾这个东西。也许存在一些可以帮助以更好的方式处理它的实用程序/帮助程序?

P.S。不要问我这个有趣的要求,它只是MaterilUI的 withStyle 功能,我想知道如何正确处理它。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用_.invokeMap()_.merge()从一组样式函数和一个主题生成组合样式的对象:

this.http.post('http://localhost:8080/project/createProject', JSON.stringify(project), 
{ 
  headers: {'Content-Type': 'application/json'} 
}).subscribe( (res) => {this.logger.info('Response: ' + res);});
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)