Skip to content

Instantly share code, notes, and snippets.

@jethrolarson
Last active August 29, 2016 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jethrolarson/668ab16657f71438e89e1567f5585ef4 to your computer and use it in GitHub Desktop.
Save jethrolarson/668ab16657f71438e89e1567f5585ef4 to your computer and use it in GitHub Desktop.
Functional Dependency Injection in JavaScript

Dependency Inversion Principle (DIP) is a design pattern popular in Object Oriented Programming but it's not alien to functional programming. Parameterizing dependencies is actually critical to maintaining functional purity--one of the most important aspects of FP.

While special dependency injection frameworks are sometimes used, a similar effect can be achieved using partial application.

// Import an arbitrary dependency to be used with a module
const someDependency = require('someDependency')
// Import our module that has a dependency
// We can apply the dependency immediately so we don't have to keep a reference to the factory.
const myMod = require('myModule')(someDependency)
//Use it
myMod.bar('do something')
// Rather than exporting the module directly you can export a function that takes your dependency and exports what you want.
// The dependency is available to functions defined this way via closure.
module.exports = (someDep) => ({
foo: () => someDep.SPECIAL_CONSTANT + 2,
bar: (str) => someDep.useTheThing(str)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment