Skip to content

Instantly share code, notes, and snippets.

@v0lkan
Last active August 29, 2015 14:02
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 v0lkan/f00d5710c8a1a24c1b6c to your computer and use it in GitHub Desktop.
Save v0lkan/f00d5710c8a1a24c1b6c to your computer and use it in GitHub Desktop.
A quick namespace resolver.
function maybe(obj, path, defaultValue) {
if (obj == null) {return undefined;}
var reduced = path.split('.').reduce(function(memo, attr) {
if (memo == null) {return undefined;}
return memo[attr];
}, obj);
return reduced === undefined ? defaultValue : reduced;
}
var test = {foo: {bar: baz: 42}};
maybe(test, 'foo.bar.baz'); // -> 42
maybe(test, 'foo.boom.baz'); // -> undefined
maybe(test, 'foo.boom.baz', 11); // -> 11
maybe(test, 'foo.bar.baz', 11); // -> 42
// Or you can call app.factories.unicornsAndRainbows.generate({args}) even when the method does not exits.
// The action will be a noop, instead of an error.
// much better than try{..}catch{...}
maybe(app, 'factory.unicornsAndRainbows.generate', $.noop)({numUnicorns:10, numRainbowColors:7});
// or you can even morph it into a utility function if you write some wire-up code.
app.maybeCall('factory.unicornsAndRainbows.generate', {numUnicorns:10, numRainbowColors:7}));
@v0lkan
Copy link
Author

v0lkan commented Jun 16, 2014

So that you don't have to write things like...

if ( test && test.foo && test.foo.bar && test.foo.bar.baz ) { doStuff( test.foo.bar.baz ); } else { doStuff( 11 ); }

@v0lkan
Copy link
Author

v0lkan commented Jun 16, 2014

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