Last active
August 29, 2015 14:02
-
-
Save v0lkan/f00d5710c8a1a24c1b6c to your computer and use it in GitHub Desktop.
A quick namespace resolver.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ); }