Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String conversion to undefined/null/number/boolean

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 = function (value){
    if (value === "undefined") return undefined;
    if (value === "null") return null;
    if (value === "true") return true;
    if (value === "false") return false;
    var v = Number (value);
    return isNaN (v) ? value : v;
};

Candidates:

//Me, Gabriel Llamas
var cast1 = function (value){
    if (value === "undefined") return undefined;
    if (value === "null") return null;
    if (value === "true") return true;
    if (value === "false") return false;
    var v = Number (value);
    return isNaN (v) ? value : v;
};

//KooiInc
var cast2 = function (value){
    var v = Number (value);
    return !isNaN(v) ? v : 
             value === "undefined" ? undefined
         : value === "null" ? null
         : value === "true" ? true
         : value === "false" ? false
         : value
};

//LightStyle
var cast3 = function (value){
    try {
        return (new Function("return " + value + ";"))();
    } catch(e) {
        return value;
    }
};

//Emmissary's proposal
var cast4 = function (value){
    if (value === "undefined") return undefined;
    try{
        return JSON.parse (value);
    }catch (e){
        return value;
    }
};

Benchmark code (using speedy):

var fn = function (cast){
    cast ("undefined");
    cast ("null");
    cast ("true");
    cast ("false");
    cast ("12");
    cast ("12.34");
    cast ("asd");
};

speedy.run ({
    "cast 1": function (){
        fn (cast1);
    },
    "cast 2": function (){
        fn (cast2);
    },
    "cast 3": function (){
        fn (cast3);
    },
    "cast 4": function (){
        fn (cast4);
    }
});

Result:

File: string-conversion.js

Node v0.10.18
V8 v3.14.5.9
Speedy v0.0.8

Benchmarks: 4
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per benchmark: ~3000ms (3s 0ms)
Total time: ~12000ms (12s 0ms)

Higher is better (ops/sec)

cast 1
  6,270,458 ± 0.2%
cast 2
  3,305,103 ± 0.0%
cast 3
  54,952 ± 0.0%
cast 4
  82,790 ± 0.4%

Elapsed time: 12109ms (12s 109ms)
like image 400
Gabriel Llamas Avatar asked Sep 14 '13 08:09

Gabriel Llamas


People also ask

How do you convert a string to a boolean in TypeScript?

To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.

How do you convert numbers to boolean?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.

Is an empty string null or undefined?

null. undefined (value of undefined is not the same as a parameter that was never defined) 0. "" (empty string)


3 Answers

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.

like image 176
Niccolò Campolungo Avatar answered Oct 06 '22 00:10

Niccolò Campolungo


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
 }
like image 26
KooiInc Avatar answered Oct 06 '22 02:10

KooiInc


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.

like image 32
suffering Avatar answered Oct 06 '22 02:10

suffering