Jacksonkr
Jacksonkr

Reputation: 32247

faster boolean from string conversion

For numbers you can do +"10" instead of Number("10") which is a chunk faster. Is there a way to do this for boolean from a string?.

Upvotes: 2

Views: 451

Answers (3)

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

If matching all case variants of the word true is the requirement, I believe using a regex is the quickest, eg:

/^true$/i.match(input)

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359966

It's silly to use a regexp. If you really only want to match the string 'true' and don't care about case sensitivity, just compare against that string:

function parseBoolean(s)
{
    return s === 'true';
}

I suppose if I were really going to play "fill in the blank" with you, I'd answer:

+"10" is to Number("10") as !!"true" is to Boolean("true")

since Boolean(x) only returns false when x is a falsy value, that is, when x ∊ {null, undefined, false, 0, ''}.

Upvotes: 5

biziclop
biziclop

Reputation: 14616

Some not-so-good and evil solutions:

window.toBool = {'false':false,'true':true};
toBool['false'] === false

eval('false') === false // don't ever do this!

JSON.parse('false')

Upvotes: 1

Related Questions