Skip to content

Instantly share code, notes, and snippets.

@karolk
Created July 27, 2012 15:08
Show Gist options
  • Save karolk/3188558 to your computer and use it in GitHub Desktop.
Save karolk/3188558 to your computer and use it in GitHub Desktop.
checking 'deep' namespaces for existence and type
(function(host) {
host.is = function is(namespace, type) {
var ret = true,
parent = host,
chunks = namespace.split('.');
chunks.forEach(function(e, i) {
if ( parent === null ) { //this has to be straight equality check, can't lookup properties on null
ret = false
return //break
}
if ( typeof parent[e] != 'undefined' || (i == chunks.length-1 && type == 'undefined') ) {
parent = parent[e]
}
else {
ret = false
return //break
}
});
if (type) {
typeof parent == type || (ret = false);
}
return ret;
};
})(this);
@karolk
Copy link
Author

karolk commented Jul 30, 2012

Example:

var Foo = {
  bar: {
    start: function() {
      alert(this.flag)
    },
    flag: false
  }
}

console.log(
    is('Foo'),                          //is Foo defined
    is('Foo.bar'),                      //is Foo.bar defined
    is('Foo.bar.start', 'function'),    //is Foo.bar.start defined and of type 'function'
    is('Foo.bar.flag'),                 //is Foo.bar.flag defined
    is('Foo.bar.flag', 'boolean'),      //is Foo.bar.flag defined and of type 'boolean'
    is('Foo.bar.stop'),                 //is Foo.bar.stop defined
    is('Foo.bar.stop', 'undefined')     //is Foo.bar.stop undefined
)

//=> true true true true true false true

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