Here is what I came up with:
function integer(x) { if (typeof x !== "number" && typeof x !== "string" || x === "") { return NaN; } else { x = Number(x); return x === Math.floor(x) ? x : NaN; } }
(Note: I updated this feature to maintain protection against white space lines. See below.)
The idea is to accept only arguments whose type is either a number or a string (but not an empty string value). It then converts to a number (if it is a string), and finally, its value is compared with the value of floor () to determine if the number is an integer or not.
integer(); // NaN integer(""); // NaN integer(null); // NaN integer(true); // NaN integer(false); // NaN integer("1a"); // NaN integer("1.3"); // NaN integer(1.3); // NaN integer(7); // 7
However, the NaN value here is “misused” because floats and strings representing floats lead to NaN, and this is technically incorrect.
Also note that due to the way strings are converted to numbers, the string argument may have trailing or leading white space or leading zeros:
integer(" 3 "); // 3 integer("0003"); // 3
Another approach ...
You can use regex if the input value is a string. This is a regular expression: /^\s*(\+|-)?\d+\s*$/ will match strings representing integers.
UPDATED FUNCTION!
function integer(x) { if ( typeof x === "string" && /^\s*(\+|-)?\d+\s*$/.test(x) ) { x = Number(x); } if ( typeof x === "number" ) { return x === Math.floor(x) ? x : NaN; } return NaN; }
This version of integer () is more restrictive since it only allows the use of strings that follow a specific pattern (which is checked using a regular expression). It gives the same results as another integer () function, except that it additionally ignores all white space lines (as indicated by @CMS).
Updated again!
I noticed @Zecc's answer and simplified the code a bit ... I think this works too:
function integer(x) { if( /^\s*(\+|-)?\d+\s*$/.test(String(x)) ){ return parseInt(x, 10); } return Number.NaN; }
This is probably not the fastest solution (in terms of performance), but I like its simplicity :)