i do not understand why we are checking against a string value in the following condition
Because c
is a character (really, a 1-character string), since that's what String.charAt
returns. That said, the isInteger
function could be written much more simply using a regex:
function isPositiveInteger(s)
{
return !!s.match(/^[0-9]+$/);
// or Rob W suggests
return /^\d+$/.test(s);
}
or you could take another approach: convert the string to a number, make sure it's positive, and make sure that the floor of the number is the same as the original (thus it's an integer):
function isPositiveInteger(s)
{
var i = +s; // convert to a number
if (i < 0) return false; // make sure it's positive
if (i != ~~i) return false; // make sure there's no decimal part
return true;
}