Search code examples
javascriptchaining

How to dynamically exclude the object from the chaininig in JavaScript?


I've got the object structure, where utils and utils.not takes the same prototype (with exist method). I simplified it for make it more clear:

var negative = true;
if(negative){
  //when negative===true, I want to run exist() through not object
  tests.utils.not.exist();
} else {
  tests.utils.exist();
}

Is there any other way to exclude not from the chain instead of using IF? If I wanted to change not object into another, eg positive, I could do this simply like that:

tests.utils[negative ? 'not':'positive'].exist();

But how can I dynamically exclude not object from the chain? My IF syntax works fine, but I just wonder if there is another (more elegant) way in JS.


Solution

  • You can use Proxies to set default behaviour and then call them the way you want take a look at the example

    var handler = {
      get: function(target, name) {
        return target.hasOwnProperty(name) ? target[name] : target["default"];
      }
    };
    
    var p = new Proxy({
    	default : {
    		exists : function(){
    			return 1;
    		}
    	},
    	not : {
    		exists : function(){
    			return 2;
    		}
    	}       
    }, handler);
    
    let negative = false;
    
    let x = p[negative === true ? "not" : "default"];
    console.log(x.exists());

    Take a look at MDN docs