loading...

Discussion on: Dependency Injection in JavaScript

Collapse
karfau profile image
Christian Bewernitz

Lets say you have this amazing util function that looks up some data in some static/global read only Map and does some calculation that you need in many places in your code base, lets imagine the following signature: function wow(number): Metric.

In some other function foo in a different module I'm doing the following to be able to use it easily, but still be able to pass a mock or stub when I want to unit-test foo without invoking wow.

In TypeScript this could look like this:

import {wow as wowGLobal} from '../../[...]';

function foo(data: PayLoad, wow = wowGlobal) {
  const metric = wow(data.x);
  [...]
}

Is this helpful?

Thread Thread
kayis profile image
K Author

Ah, got it.

I probably would have implemented with a curried function.

const createFoo = wow => (data: PayLoad) => {
  const metric = wow(data.x);
  ...
}

in the regular place I'd use

foo = createFoo(wowGlobal);

and for testing something different, but I guess your way works too, it's just a bit more implicit.

Thread Thread
restuta profile image
Anton Vynogradenko

To be annoyingly pedantic, createFoo above is not a curried function, because it can't be called like createFoo(wow, data) and like createFoo(wow, data) at the same time, it's a higher order function with aurity of 1

Thread Thread
kayis profile image
K Author

I allow it!