Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
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