Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created August 6, 2020 15:24
Show Gist options
  • Save mattmccray/fe66ef32dfc9ba2d673e2700d0ba11fc to your computer and use it in GitHub Desktop.
Save mattmccray/fe66ef32dfc9ba2d673e2700d0ba11fc to your computer and use it in GitHub Desktop.
Micro context
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