JSFiddle - React, Tailwind, and code Playground
HTML
<div id="tests-output">Result:</div>
CSS
.test {
font-family: monospace;
margin: 2px;
}
JavaScript
// Raw solution
function isInt1(value) {
return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10));
}
// Bitwise
// Simple parse and check
function isInt2(value) {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
// Short-circuiting, and saving a parse operation
function isInt3(value) {
if (isNaN(value)) {
return false
}
var x = parseFloat(value);
return (x | 0) === x
}
// Both in one shot
function isInt4(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}
// Testing:
var tests = [
[42, true],
["42", true],
[4e2, true],
["4e2", true],
[" 1 ", true],
["", false],
[" ", false],
[42.1, false],
[null, false],
[NaN, false],
["1 a", false],
["4e2a", false]
];
var $container = $("#tests-output"),
consoleLine = "<p class=\"test\"></p>";
$container.append("<p class=\"test\">Int1 Int2 Int3 Int4</p>")
$container.append("----------------------------")
function ouput(a,b,c,d) {
$container.append($(consoleLine).html(a + " " + b + " " + c + " " + d));
}
for (var i = 0; i < tests.length; i++) {
var pair = tests[i];
var result1 = isInt1(pair[0]) == pair[1];
var result2 = isInt2(pair[0]) == pair[1];
var result3 = isInt3(pair[0]) == pair[1];
var result4 = isInt4(pair[0]) == pair[1];
ouput(result1, result2, result1, result4);
}