Created
September 18, 2015 22:11
-
-
Save chuck0523/5dc7f678c60b81077d45 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.19 revision | |
convert.js enables you to convert date to other data type | |
*/ | |
(function(w){ | |
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\');', | |
canBeArgs = '* You can also use 2nd arg as data type.', | |
typeErr = '* Type error! number, boolean or string are valid as 2nd arg.', | |
something = 'Something happened, something'; | |
var hasData = function(x) { | |
return x !== undefined && | |
( x || x === null || x === 0 || isNaN(x) || x === '' ); | |
}; | |
var convert = function(x, y) { | |
switch(y) { | |
case 'number': | |
return parseInt(x); | |
case 'boolean': | |
return !!x; | |
case 'string': | |
return x + ''; | |
case undefined: | |
log(canBeArgs); | |
return '{ number : ' + -(-x) + | |
' , boolean : ' + !!x + | |
' , string : ' + x + '' + ' }'; | |
default: | |
log(typeErr); | |
return null; | |
} | |
}; | |
var showResult = function(x, y) { | |
var | |
data = ( x !== '' ) ? x : '(empty string)' ; | |
dataType = ( y ) ? '(' + y + ')' : '' ; | |
convertedData = convert(x, y); | |
convertedData !== null && log(dataType + data + ' -> ' + convertedData ); | |
}; | |
var cnv = function(x, y) { | |
hasData(x) ? showResult(x, y) : log(usage); | |
}; | |
(w.cnv === undefined) && ( w.cnv = cnv ) | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment