0

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 !

3
  • You question is unclear. But it seems you want to create a and b functions dynamically? Commented Mar 7, 2019 at 13:22
  • I've updated the description, it was in fact a little blurry... Commented Mar 7, 2019 at 15:52
  • Where "general" argument are passed in ? this is not passed to the original funcions (info, warn) Commented Mar 7, 2019 at 17:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer but it's not what i'm looking for. I've updated the description to be more precise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.