Last active
February 14, 2019 03:53
-
-
Save rjhilgefort/d6d4259dbef849175fcfab84fdb0d078 to your computer and use it in GitHub Desktop.
This file contains 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
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