When you write a tokenizer, for example for a math expression evaluator, then it is unavoidable to find the category of a single character, whether it’s a number, an operator, etc. While the most logical way is to use regular expression, what if you would like to do it without one?
A typical JavaScript function to carry out this monumental job is as follows:
function isDigit(ch)
{
var c = ch.charCodeAt();
return (c >= 48) && (c < = 57);
}
If you want to use some slightly complicated branch statement, then do something like this (or again, a version which uses the character code instead):
function isDigit(ch)
{
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}
Should you know the internals of modern JavaScript engines, the above two forms translate to a nicely optimized form, ready to be executed at a blazing speed by the engine.
However, if you don’t really care about microsecond-level of performance (your bottleneck is probably somewhere else, not in the above innocent function), an alternative would be (warning: careful JavaScript experts might be provoked into another variant using the property lookup of a constant object):
function isDigit(ch)
{
return '0123456789'.indexOf(ch) >= ;
}
String searching can’t beat the speed of simple integer comparison yet from time to time I find the construct depicted above is just beautiful and easy on eyes.
Your take?