Home > front end >  Can curry functions be executed half way?
Can curry functions be executed half way?

Time:05-31

Lets say I have a function like this:

function foo(){
  return () => {
    return "bar"
  }
}

foo()() // => "bar"

Is there a way for this to return something other than a function without the use of a parameter?

foo()() // => "bar"
foo()   // => "foo"

CodePudding user response:

No. If the value returned must be callable later, then it has to be a function - no exceptions.

You could put a property on the function, though.

function foo(){
  return Object.assign(
    () => {
      return "bar"
    },
    { prop: 'bar' }
  );
}

console.log(foo()());
console.log(foo().prop);

Or return both a function and something else.

function foo(){
  return [
    () => {
      return "bar"
    },
    'bar'
  ];
}

const [fn, val] = foo();
console.log(fn());
console.log(val);

  • Related