Skip to content

Instantly share code, notes, and snippets.

@geovanisouza92
Last active October 6, 2017 16:00
Show Gist options
  • Save geovanisouza92/ad0e48143bdb6b9cc423b8d53bd583c2 to your computer and use it in GitHub Desktop.
Save geovanisouza92/ad0e48143bdb6b9cc423b8d53bd583c2 to your computer and use it in GitHub Desktop.
Golang net/context equivalent for JS
function background() {
const m = {}
function create(p) {
return {
withValue(prop, value) {
// Create a new "memory"
const p1 = Object.assign({}, p)
m[prop] = m[prop] || []
p1[prop] = m[prop].push(value) - 1
// Create the child context
let child = create(p1)
// Apply existing accessors
const parent = this
Object.getOwnPropertyNames(parent).forEach(name => {
if (name === 'withValue' || name === 'inspect' || name === prop) {
return
}
const descriptor = Object.getOwnPropertyDescriptor(parent, name)
Object.defineProperty(child, name, descriptor)
})
// Define/overwrite a new accessor for prop
Object.defineProperty(child, prop, {
configurable: false,
enumerable: true,
get() {
return m[prop][p1[prop]]
}
})
return child
},
inspect() {
return {p, m}
}
}
}
return create({})
}
const c1 = background()
// console.log('c1', c1.inspect())
console.log('c1', JSON.stringify(c1))
const c2 = c1.withValue('foo', 'bar')
// console.log('c2', c2.inspect())
console.log('c2', JSON.stringify(c2), 'foo', c2.foo) // 'bar'
const c3 = c2.withValue('foo', 'baz').withValue('lorem', 'ipsum')
// console.log('c3', c3.inspect())
console.log('c3', JSON.stringify(c3), 'foo:', c3.foo) // 'baz'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment