Skip to content

Instantly share code, notes, and snippets.

@chuck0523

chuck0523/convert3.js

Last active Sep 7, 2015
Embed
What would you like to do?
/*
convert.js by chuck
2015.9.5 start to work
2015.9.8 revision
convert.js enables you to convert date to other data type
*/
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);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment