简体   繁体   中英

Javascript reusable functions

I have 2 functions with the same logic (eg: printing in console multiple concatenated elements) but with one specificity. The easy way is to specify the specificity in parameter, like this :

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")

However, i would like to handle this specificity with a function, not as a parameter, like this :

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")

Problem is, when i want to add/remove a parameter, for example, i need to add/remove it everywhere

Is there any way to do it better ?

Something like this :

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")

Thanks in advance !

Maybe what you are looking for are curry functions :

// 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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM