Skip to content

Instantly share code, notes, and snippets.

@josser

josser/proxy.js

Last active Apr 30, 2020
Embed
What would you like to do?
// @ts-nocheck
import vm from 'vm'
import _debug from 'debug'
const debug = _debug('wf:enhancer')
class WObject {
constructor(source: any) {
this._w = source
return new Proxy(this, {
get(target, property) {
debug('Property %s', property)
debug('Target: %o', target)
if (typeof Reflect.get(target, property) === 'function') {
return (...args) => {
debug('in proxy %o', args)
return Reflect.get(target, property).apply(target, args)
}
}
if (Reflect.has(target._w), property) {
const value = Reflect.get(target._w, property)
switch (true) {
case Array.isArray(value): {
return new WArray(value)
}
default:
return new WObject(value)
}
} else {
throw new Error(`Undefined property: ${property}`)
}
}
})
}
eeq(v: any): boolean {
debug('eeq called: %s', v)
debug('valueOf: %s', this._w)
return this._w === v
}
}
class WArray extends WObject {
size(): numeber {
debug('Array size:', this._w)
return new WObject(this._w.length)
}
}
const params = new WObject({ test: { cool: { foo: [1,2,[9,8,7,6],4] } } });
const ctx = vm.createContext({ console, params })
vm.runInContext('console.log(params); if (params.test.cool.foo[2].filter(v => (v > 7)).size().eeq(4)) { console.log("test") }', ctx)
@josser

This comment has been minimized.

Copy link
Owner Author

@josser josser commented Apr 30, 2020

$ DEBUG=wf:* ts-node src/enhancer.ts
WObject { _w: { test: { cool: [Object] } } }
WObject { _w: { test: { cool: [Object] } } }
wf:enhancer Property test +0ms
wf:enhancer Target: WObject { _w: { test: { cool: [Object] } } } +0ms
wf:enhancer Property cool +0ms
wf:enhancer Target: WObject { _w: { cool: { foo: 4 } } } +0ms
wf:enhancer Property foo +0ms
wf:enhancer Target: WObject { _w: { foo: 4 } } +0ms
wf:enhancer Property eeq +1ms
wf:enhancer Target: WObject { _w: 4 } +0ms
wf:enhancer in proxy [ 4 ] +0ms
wf:enhancer eeq called: 4 +0ms
wf:enhancer valueOf: 4 +0ms
test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment