Last active
April 12, 2024 02:59
-
-
Save rndme/f8fcf587c592ccdc977a90f961f012c2 to your computer and use it in GitHub Desktop.
tiny getter/setter helper for observables, polyfilling, deprecation, interfacing, etc
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
function odp(obj, get, set, isHidden){ | |
Object.defineProperty(obj, /^\w+/.exec(get), {get, set, enumerable: !isHidden}); | |
return odp.bind(this, obj); | |
} | |
// example usage in a class | |
class Ohm { | |
constructor(V, I){ | |
odp(this, _=>Ohm) | |
( v=>V, _=>V=_ ) | |
( i=>I, _=>I=_ ) | |
( w=>V*I, _=>I=_/V ) | |
( r=>V/I, _=>I=V/_ ); | |
} | |
} | |
var x = new Ohm(5, 2); // == {"v":5,"i":2,"w":10,"r":2.5} | |
x.r=10; | |
console.log(JSON.stringify(x)); // == {"v":5,"i":0.5,"w":2.5,"r":10} | |
// example usage in a factory | |
function Ohm (V, I, _){ | |
odp(_={}, _=>Ohm) | |
( v=>V, _=>V=_ ) | |
( i=>I, _=>I=_ ) | |
( w=>V*I, _=>I=_/V ) | |
( r=>V/I, _=>I=V/_ ); | |
return _; | |
} | |
var y = Ohm(5, 2); // == {"v":5,"i":2,"w":10,"r":2.5} | |
y.r=10; | |
console.log(JSON.stringify(y)); // == {"v":5,"i":0.5,"w":2.5,"r":10} | |
// example usage w/ state in lexical scope | |
let V=5, I=2, z={}; | |
odp( z, _=>odp ) | |
( v=>V, _=>V=_ ) | |
( i=>I, _=>I=_ ) | |
( w=>V*I, _=>I=_/V ) | |
( r=>V/I, _=>I=V/_ ); | |
console.log(JSON.stringify(z)); // == {"v":5,"i":2,"w":10,"r":2.5} | |
z.r=10; | |
console.log(JSON.stringify(z)); // == {"v":5,"i":0.5,"w":2.5,"r":10} | |
/* compare to inline getters and setters: | |
function Ohm(o){ | |
return Object.assign({ | |
get v(){return o.v;}, | |
get i(){return o.i;}, | |
get w(){return o.v * o.i}, | |
get r(){return o.v / o.i}, | |
set v(val){return o.v=val;}, | |
set i(val){return o.i=val;}, | |
set r(val){ o.i = o.v / val;}, | |
set w(val){ o.i = val / o.v;}, | |
}, o); | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment