-
-
Save Couto/0ec37ef6eda55dd8bf71 to your computer and use it in GitHub Desktop.
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 trim (str) { | |
if (typeof str !== 'string') { throw new Error('Invalid argument type'); } | |
// do trimming | |
return str; | |
} |
PS: notice that toNumber
and toArray
needs a lot of type checks.. the thing is, that by abstracting the checks into a few helper functions I avoid littering my code with type checks, I can simply use it as if data was always the way I want to. IMO the minority of the functions should have type checks, not saying that they aren't useful.
PPS: my application code rarely have toNumber
, toArray
and toString
calls, these are more useful for helpers/libraries since you never know how they will be called. For most cases you can just assume the proper data will be passed and if you receive the wrong kind of data it will throw errors automatically (undefined is not a function
).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you don't need to fail early in most cases. in fact for trimming (and all string methods) on MOUT I used a
toString
function to make sure it doesn't throw errors:that allows us to pass any object that implements a
toString
method and avoids naive mistakes like passingnull
orundefined
(and always expecting a string back).I even implemented a safe
upperCase
andlowerCase
methods just to avoid bureaucracy: http://moutjs.com/docs/latest/string.html#upperCasenowadays when I need to make sure I have a string I just call
toString
.. if I need an array I calltoArray
, that simplified my code A LOT. I usually only throw errors for cases where there is really no easy way to recover.PS: the likelihood of passing an object to
trim
is not so high, but the likelihood of passing a number ornull
orundefined
is pretty high when data is coming from external sources.