Skip to content

Instantly share code, notes, and snippets.

@RangerMauve
Last active December 30, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RangerMauve/7839994 to your computer and use it in GitHub Desktop.
Save RangerMauve/7839994 to your computer and use it in GitHub Desktop.
This is a neat idea I had for having variables that act like primitive values but are actually functions. Useful for having complex variables that automagically update.
// This calls the function whenever a primitive is needed
function R(fn){
return {
valueOf:fn,
toString:function(){
return fn()+"";
}
};
}
var t = 0;
var x = R(function(){
return Math.sin(t);
});
// You can combine them by using R each time
var y = R(function(){
return x / 2;
});
log(x) // 0
// Changes in t affect x right away
t = Math.PI/2;
log(x); // 1
// Works as expected and calls x/2
log(y); // 0.5
// Values are passed by reference
var z = y;
log(z); // 0.5
t = 0;
log(z); // 0
@RangerMauve
Copy link
Author

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