HardPro challengePythonJavaScriptTypeScript

Dependency Injection Container

PatternsObjectsDependency Injection

Implement a simple DI container:

const container = new Container();
container.register('name', factoryExpr, deps?)
container.resolve('name')  // instantiate with resolved deps
  • register(name, factoryExpr, deps) — register a factory **expression

string** (e.g. '() => 42' or '(x) => x * 2') with optional dependency
names. Convert it to a function via new Function('return ' + expr)().

  • resolve(name) — resolve the service, auto-resolving its dependencies

recursively. Throw on circular deps or missing registrations.

solve(registrations, target) replays registrations then resolves a service.

Each registration is a tuple [name, factoryExpr, deps?].

Sample tests

Test #1Two-level dependency graph: c depends on a and b
Input: [[["a","() => 1",[]],["b","(a) => a + 2",["a"]],["c","(a, b) => a + b",["a","b"]]],"c"]
Output: {"ok":true,"value":4}
Test #2Three-level chain
Input: [[["base","() => 'base'",[]],["mid","(b) => b + '-mid'",["base"]],["top","(m) => m + '-top'",["mid"]]],"top"]
Output: {"ok":true,"value":"base-mid-top"}
Test #3Simple service, no deps
Input: [[["a","() => 42",[]]],"a"]
Output: {"ok":true,"value":42}
Test #4Service with one dependency
Input: [[["x","() => 10",[]],["y","(x) => x * 2",["x"]]],"y"]
Output: {"ok":true,"value":20}
Test #5Missing registration throws
Input: [[],"missing"]
Output: {"ok":false,"error":"Unknown service: missing"}