Created
August 6, 2020 15:24
-
-
Save mattmccray/fe66ef32dfc9ba2d673e2700d0ba11fc to your computer and use it in GitHub Desktop.
Micro context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let _stack = [{}] | |
export function getContext(key) { | |
return _stack[0][key] | |
} | |
export function setContext(key, value) { | |
_stack[0][key] = value | |
} | |
export function withNestedContext(fn) { | |
return (...args) => { | |
_pushContextStack() | |
const results = fn(...args) | |
_popContextStack() | |
return results | |
} | |
} | |
export function _pushContextStack() { | |
_stack.unshift(Object.create(_stack[0])) | |
} | |
export function _popContextStack() { | |
if (_stack.length === 1) return // Don't remove the root context | |
_stack.shift() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment