Skip to content

Latest commit

 

History

History

function-resolve

➡️ Function Resolve

#container #dependency #functional

Open in CodeSandbox Develop on localhost

IoC container resolver for functional programming

This algorithm was designed while working on rx-elevators. It wraps a dependency container, in this case inversify but could be others like tsyringe, and exposes resolve to enable a functional dependency resolution syntax. In summary, it enables functional inversion of control, or IoC without classes, similar to React's Context. See Context vs Containers for background.

In more capable functional programming languages inversion of control is achieved by using implicit parameters, or reader monads, but TypeScript does not provide such feature practically. IoC can be easily achieved with JavaScript, but many methods require dynamic resolution ("stringly typed", and/or proxies) making it harder to correctly statically type code. In JavaScript it is common to find solutions like inversify for class based IoC, and React Context for function based IoC. Kotlin provides a practical solution with context receivers, and Python with context-local variables


import { resolve, Use } from '/src'
import { Container } from 'inversify'

const container = new Container()

type Sum = (x: number) => (y: number) => number

type SumX = (x: number) => number

const useSum: Use<Sum> = () => {
  return (x) => (y) => x + y
}

const useSum10: Use<SumX> = (resolve) => {
  const sum = resolve(useSum)
  return sum(10)
}

test('resolving dependencies', () => {
  const sum10 = resolve(container)(useSum10)
  expect(sum10(20)).toBe(30)
})