Created
September 7, 2015 04:47
-
-
Save chuck0523/b50dab2dd825b02ed6a5 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
/* | |
convert.js by chuck | |
2015.9.5 start to work | |
2015.9.7 revision | |
convert.js enables you to convert date to other data type | |
TODO : | |
'tolerantCheck' is not good enough as a name of the function. | |
{y !== undefined} in 'illegalDataType' is actually not necessary | |
'' (empty string) and 'undefined' isn't valid corrently. | |
Maybe same data type convert should be error | |
*/ | |
var log = function(x) {console.log(x);} | |
var | |
usage = "Usage : \n 1st arg : data to convert. \n 2nd arg : data type to convert(not necessary).\n ex) cnv(false,'number');", | |
soleArg = "You can also use 2nd arg as data type.", | |
typeErr = 'type error! Only number, boolean or string are valid.'; | |
var tolerantCheck = function(x) { | |
return x !== undefined && (x === 0 || isNaN(x) || x === null); | |
}; | |
var illegalDataType = function(y) { | |
var illegal = y !== undefined && y !== 'number' && y !== 'boolean' && y !== 'string'; | |
illegal && log(typeErr); | |
return illegal; | |
}; | |
var hasArgs = function(x, y) { | |
var | |
hasX = !!x || tolerantCheck(x), | |
hasY = !!y, | |
el = (!hasX && !hasY) ? usage : (hasX && !hasY) ? soleArg : null; | |
el && log(el); | |
return hasX ; | |
}; | |
var convert = function(x, y) { | |
var rtn; | |
switch(y){ | |
case 'number': | |
rtn = parseInt(x); | |
break; | |
case 'boolean': | |
rtn = !!x; | |
break; | |
case 'string': | |
rtn = x + ''; | |
break; | |
case undefined: | |
rtn = '{ number : ' + parseInt(x) + ' , boolean : ' + !!x + ' , string : ' + x + ' }'; | |
break; | |
default: | |
} | |
return rtn; | |
}; | |
var cnv = function(x, y) { | |
if( !hasArgs(x, y) || illegalDataType(y) ) { | |
return false; | |
} | |
var dataType = ( y ) ? '(' + y + ')' : null ; | |
log(dataType + x + ' -> ' + convert(x, y) ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment