Last active
March 3, 2016 14:13
-
-
Save bradoyler/bda5ae43556b9345a640 to your computer and use it in GitHub Desktop.
Handy Util (Node.js) for when you expect an Array....and want to avoid "Object.forEach is not a function" errors.
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
var forceArray = function(val) { | |
if ( Array.isArray( val ) ) return val; | |
if ( !val ) return []; | |
return [ val ]; | |
} | |
// usage: | |
var test1 = {id:1}; | |
forceArray(test1) // returns [{id:1}] | |
var test2 = "test"; | |
forceArray(test2) // returns ["test"] | |
var test3; | |
forceArray(test3) // returns [] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment