Skip to content

Instantly share code, notes, and snippets.

@spiralx
Created January 26, 2016 18:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spiralx/dd082079a142beece276 to your computer and use it in GitHub Desktop.
Save spiralx/dd082079a142beece276 to your computer and use it in GitHub Desktop.
Use ES6 Proxy to attach computed properties
'use strict';
const VALUE = Symbol.for('value')
function addComputedProperty(obj, name, func) {
let _computed = func(obj)
return new Proxy(obj, {
get(target, key, receiver) {
if (key === name) {
return _computed
}
return Reflect.get(target, key, receiver)
},
set(target, key, value, receiver) {
if (key === name) {
throw new ReferenceError(`Cannot set computed property "${name}"`)
}
if (value === Reflect.get(target, key, receiver)) {
return true
}
Reflect.set(target, key, value, receiver)
_computed = func(target, key)
}
})
}
let q = addComputedProperty({}, VALUE, obj => {
const keys = Object.keys(obj)
if (keys.length === 0) {
return ''
}
return '?' + keys.map(k => k + '=' + encodeURIComponent(obj[k])).join('&')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment