Do you know any better and faster way to convert a string to the type it represents?
I\'ve always been using this function:
var convertType = functio
How about:
var convertType = function (value){
var values = {undefined: undefined, null: null, true: true, false: false}
,isNumber = !isNaN(+(value));
return isNumber && +(value) || !(value in values) && value || values[value];
};
convertType('null'); //=> null
convertType('something'); //=> "something"
convertType('57.321'); //=> 57.321
convertType('undefined'); //=> undefined
This seems faster @ jsPerf
var convertType = function (value){
var v = Number (value);
return !isNaN(v) ? v :
value === "undefined" ? undefined
: value === "null" ? null
: value === "true" ? true
: value === "false" ? false
: value
}
This is a simple function which involves the use of a function to evaluate the strings. This way you can remove the part of cases' "switch". Be aware that this handles also assignments to global variables, so I recommend it only if you know anytime where is the source from(don't allow users to use this function!)
var convertType = function (value){
try {
return (new Function("return " + value + ";"))();
} catch(e) {
return value;
}
};
You can see the jsfiddle here.
var string2literal = function (value){
var maps = {
"NaN": NaN,
"null": null,
"undefined": undefined,
"Infinity": Infinity,
"-Infinity": -Infinity
}
return ((value in maps) ? maps[value] : value);
};
There are many weird rules in dynamic data type converting, just map it.