Created
May 26, 2016 17:13
-
-
Save davidsharp/6dd2a47e389f734ccc79766e840f4190 to your computer and use it in GitHub Desktop.
A helper 'library' for checking a variable's type, and returning the value or false, for some nice '||' chaining
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
//ES6? Use const {ifString} = ifUseful | |
//Otherwise just rename it, or crib the bits you want | |
//Why? So you can do stuff like -> `let foo = ifString(bar)||ifArray(bar).join('! ')||'Pretty useful!' ` | |
const ifUseful={ | |
ifString:function(v){return (typeof v === 'string'?v:false);}, | |
ifArray:function(v){return (Array.isArray(v)?v:false);}, | |
//What if you want something else? A single param gives you your own function! | |
ifTypeOf:function(type,v){return v?(typeof v === type?v:false):function(_v){return (typeof _v === type?_v:false);}}, | |
ifInstanceOf:function(inst,v){return v?(v instanceof inst?v:false):function(_v){return (_v instanceof inst?_v:false);}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment