Javascript可重用功能

时间:2019-03-07 13:08:38

标签: javascript function

我有2个功能具有相同的逻辑(例如:在控制台中打印多个串联的元素),但具有一种特殊性。简单的方法是在参数中指定特异性,例如:

function baseLogic (specific, general) {
  // ... many processes before here
  if(specific == "info") console.info(general)
  if(specific == "warn") console.warn(general)
}

// Calls
baseLogic("info", "foo")
baseLogic("warn", "bar")

但是,我想使用函数而不是像这样处理这种特异性:

function baseLogic (specific, general) {
  // ... many processes before here
  if(specific == "info") console.info(general)
  if(specific == "warn") console.warn(general)
}

function info(general) {
  baseLogic("info", general)
}

function warn(general) {
  baseLogic("warn", general)
}

// Calls
info("foo")
warn("foo")

问题是,例如,当我想添加/删除参数时,我需要在各处添加/删除参数

有什么方法可以做得更好?

类似这样的东西:

function baseLogic (specific, general) {
  // ... many processes before here
  if(specific == "info") console.info(general)
  if(specific == "warn") console.warn(general)
}
info = baseLogic("info")
warn = baseLogic("warn")

// Calls
info("foo")
warn("bar")

谢谢!

1 个答案:

答案 0 :(得分:1)

也许您正在寻找的是 curry函数

// no curry
const sum = (a, b) => a + b

// no curry usage
sum(3, 4)

// curry
const sum = a => b => a + b

// curry usage
sum (2)(1);

参考:https://medium.com/front-end-weekly/javascript-es6-curry-functions-with-practical-examples-6ba2ced003b1