Created
January 27, 2017 18:07
-
-
Save defvol/3a708d18957827949689d4cc58cc10f5 to your computer and use it in GitHub Desktop.
Wrapper to handle accessing undefined properties on a nested object (catches TypeErrors)
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
/** | |
* Add a standard error handling routing when accessing nested keys | |
* On TypeError (accessing undefined property) it will return empty array | |
* Will also take care of wrapping single elements in an array | |
* usage: safeparse(() => parsedXml.status.events.event) | |
* @param {Function} accessor just returns a nested key | |
* @returns {Array} | |
*/ | |
function safeparse (accessor) { | |
try { | |
return [].concat(accessor()) | |
} catch (e) { | |
return [] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment