dimanche 27 mai 2018

Does ES6 provide a way to resolve a maybe-function into its result?

I occasionally write code that looks like this:

constructor(thing) {
    this.thing = thing.constructor === Function ? thing : () => thing;
}

This lets the caller provide a value directly if they know it won't change. I'm okay with this solution, but it's too copy-and-pasty.

Does ES6 provide a more elegant way to do this? I'm imagining something analogous to Promise.resolve(maybePromise) for functions, but Function.resolve(maybeFunc) doesn't exist.

Alternatively - is there a better pattern for this? I can require that thing always be a function, but that seems cumbersome for the caller.

Aucun commentaire:

Enregistrer un commentaire