Skip to content

Instantly share code, notes, and snippets.

@rjhilgefort
Last active February 14, 2019 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjhilgefort/d6d4259dbef849175fcfab84fdb0d078 to your computer and use it in GitHub Desktop.
Save rjhilgefort/d6d4259dbef849175fcfab84fdb0d078 to your computer and use it in GitHub Desktop.
const { log, clear } = console
clear()
class Foo {
constructor() {
this.state = {}
this.util = {
nested: {
mergeRight,
identity,
}
}
}
update(x) {
this.state = this.util.nested.mergeRight(
this.state,
this.util.nested.identity(x),
)
}
log() {
log(this.state)
}
updateLog(x) {
this.update(x)
this.log()
}
}
// Spec :: { [String]: (Function -> (...args) -> Any) }
// makeProxy :: [String] -> Spec -> Instance|Object -> Proxy
const makeProxy = curry((path, spec, data) =>
new Proxy(data, {
get: (target, propKey, reciever) =>
is(String)(head(path))
? equals(head(path), propKey)
? makeProxy(tail(path), spec, target[propKey])
: target[propKey]
: includes(propKey, keys(spec))
? spec[propKey](Reflect.get(target, propKey, reciever))
: target[propKey]
})
)
class Baz {
constructor(foo, rabbit) {
this.foo = makeProxy(
['util', 'nested'],
{
mergeRight: (method) => (...args) => {
const result = method(...args)
log(`mergeRight interception`)
return result
},
identity: (method) => (...args) => {
const result = method(...args)
log(`identity interception`)
return result
},
},
foo
)
}
updateLog(x) {
this.foo.updateLog(x)
}
}
const foo = new Foo()
const bar = new Baz(foo)
bar.updateLog({ one: 'one' })
bar.updateLog({ two: 'two' })
bar.updateLog({ one: 'foo' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment