1

If I have a statement like:

public startDate = this.formatDate(new Date());

I would like to instead of passing new Date(), pass a date created by a function. I know I can do:

public startDate = this.formatDate(this.getDateFunc());

But is there a way to do it with a lambda function? I tried looking it up, but all the posts I found were talking about function as a parameter in the definition.

I want to do something like:

public startDate = this.formatDate(() => {...});

  • 2
    "*But is there a way to do it with a lambda function? I tried looking it up, but all the posts I found were talking about function as a parameter in the definition*" lambdas (arrow functions) **are** functions. [There are some differences](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) but none that probably matter for having one as a parameter. – VLAZ Sep 14 '20 at 18:06
  • 1
    ^ Note that an arrow function is not necessarily a lambda. A lambda is an anonymous function. When you save a arrow function into a variable it's no longer anonymous, thus no longer a lambda. For example `n => n * 2` is a lambda, but `const double = n => n * 2` is not a lambda. Some might say that the latter is still an unnamed function and thus a lambda, but this depends on your definition of anonymous. – 3limin4t0r Sep 14 '20 at 18:27
  • @VLAZ thanks, very helpful. So basically, in any scenario where you could syntactically use a function reference, you can also use a arrow function? – rustytoaster21 Sep 14 '20 at 18:33
  • @rustytoaster21 correct. There is no difference between functions and arrow functions as far as when can they be used. The difference is how they interact with other stuff - mostly arrow functions don't have their own `this` but use the lexical one, while normal functions can have their own `this` value. But that's not always relevant - if you take a parameter `fn` and execute it as `fn(someArg)` it would still work whether `fn` is an arrow function or a normal function. – VLAZ Sep 14 '20 at 18:36

3 Answers3

0
class A {
  public startDate = this.dateFactory();

  constructor(
    private dateFactory,
  ) {}

  ...
}
// somewhere in code
new A(() => new Date());
Xesenix
  • 2,418
  • 15
  • 30
0

Assuming, from your example, that you're wanting an anonymous function call. If so, yes, you can do this with an IIFE:

public startDate = this.formatDate(
    (() => {
        // do some other stuff
        return new Date(/* ...args */)
    })()
)

However, it's typically better for readability to name the function.

Lionel Rowe
  • 5,164
  • 1
  • 14
  • 27
0

type GetDate = () => Date

const formatDate = (getDate: GetDate) => {
 const date = getDate()
 // formate date
 
}

// usage
const getDateFromInternet = () => API.getDate() // imaginary API which fetches date

const formattedDate = formatDate(getDateFromInternet)
Pritam Kadam
  • 2,388
  • 8
  • 16