MediumJavaScriptTypeScript

Vue provide() / inject() — Component DI

VueVue.jsprovideinjectDependency InjectionJavaScript

Vue's provide/inject is a lightweight DI system that lets ancestor components share values with any descendant without prop drilling.

// Parent
const root = createContext();
setCurrentContext(root);
provide('theme', 'dark');
provide('locale', 'en');

// Grandchild (3 levels deep)
const grandchild = createContext(child);
setCurrentContext(grandchild);
inject('theme');  // → 'dark'  (inherited from root)
inject('locale'); // → 'en'   (inherited from root)

// Child overrides
setCurrentContext(child);
provide('theme', 'light');
setCurrentContext(grandchild);
inject('theme');  // → 'light' (nearest ancestor wins)

Rules

1. inject(key) walks up the context chain — the nearest ancestor that provide()d the key wins.
2. A sibling context does not inherit from another sibling's provide().
3. inject(key) returns undefined when the key is not found.

Your task

Implement createContext(parent?), provide(key, value), inject(key), and setCurrentContext(ctx).

The solve(op, ...args) harness is provided — do not modify it.

Sample tests

Test #1inject() finds a value in the current context
Input: ["basic","theme","dark"]
Output: "dark"
Test #2inject() falls back to parent context
Input: ["inherit","color","red"]
Output: "red"
Test #3child provide() overrides ancestor
Input: ["override","size","lg","sm"]
Output: "sm"
Test #4inject() returns undefined for unknown keys
Input: ["not-found"]
Output: null
Test #5sibling context does not inherit from another sibling
Input: ["no-leak","user","alice","bob"]
Output: "alice"