Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Was variable x ever true?

In Javascript, is there a good way to check if a variable was ever a true, (or any value), in the entire session? The best way I can think of right now is to perform a regular check like this, recording the truthiness in another variable:

if (variable){
  variablewasevertrue = true;
}

Then when I want to know if the original variable was ever true, I check if the new variablewasevertrue is true or undefined. There's nothing more graceful like if (variable was ever true){ is there? That doesn't seem very Javascript-y.

like image 469
Artur Sapek Avatar asked Nov 28 '22 18:11

Artur Sapek


2 Answers

No there is no if (variable was ever true) facility in the language. Variables store values, not history.

Intercepting values as they're assigned and checking is the only way to do it. If the variable is really a property (e.g. a global variable is a property of the global object) you can intercept changes easily using setters.

So to have a history keeping global variable you could do

var hasEverBeenTruthy = false;
(function () {
  var value;
  Object.defineProperty(window, "myGlobal", {
    "get": function () { return value; },
    "set": function (newval) {
      if (newval) { hasEverBeenTruthy = true; }
      value = newval;
    }
  });
})();

This will work on modern browsers, and there are __defineSetter__ variants on many older browsers.

like image 66
Mike Samuel Avatar answered Dec 08 '22 00:12

Mike Samuel


Variables store value, not a history of a memory location. If you want to do something like this, I would suggest you use an Object of some sort:

var x = {
    value: false,
    history: [],
    set: function(val){
        history.push(this.value);
        this.value = val;
    },
    wasEver: function(val){
        return this.history.indexOf(val) >= 0;
    }
};

Then you can use the object like so:

x.set(false);
x.value; //returns false

x.set(true);
x.value; //returns true

x.wasEver(true); // returns true
x.wasEver(false); //returns true
x.wasEver("hello"); //returns false

This gives each object it's own history (as in, it can check multiple values, not just one - as with the getter/setter stuff mentioned in other answers), and is guaranteed to work in any scope, as all functionality is contained within the defined object.

like image 28
Mike Trpcic Avatar answered Dec 08 '22 00:12

Mike Trpcic