Created
January 26, 2016 18:56
-
-
Save spiralx/dd082079a142beece276 to your computer and use it in GitHub Desktop.
Use ES6 Proxy to attach computed properties
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
'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