Created
September 22, 2019 17:54
-
-
Save ramsunvtech/654d6166fc45a2a20e80f89b005280d4 to your computer and use it in GitHub Desktop.
isValidNumber.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Validate if a given string can be interpreted as a decimal number. | |
Some examples: | |
"0" => true | |
" 0.1 " => true | |
"abc" => false | |
"1 a" => false | |
"2e10" => true | |
" -90e3 " => true | |
" 1e" => false | |
"e3" => false | |
" 6e-1" => true | |
" 99e2.5 " => false | |
"53.5e93" => true | |
" --6 " => false | |
"-+3" => false | |
"95a54e53" => false | |
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: | |
Numbers 0-9 | |
Exponent - "e" | |
Positive/negative sign - "+"/"-" | |
Decimal point - "." | |
Of course, the context of these characters also matters in the input. | |
*/ | |
/** | |
* @param {string} s | |
* @return {boolean} | |
*/ | |
var isNumber = function(s = '') { | |
function trim(s = '') { | |
let startIndex = -1, endIndex = -1; | |
let leftTrimmed = '', trimmed = ''; | |
for(let i = 0; i < s.length; i++) { | |
if(s[i] !== ' ') { | |
startIndex = i; | |
break; | |
} | |
} | |
for(let j = s.length -1; j > -1; j--) { | |
if(s[j] !== ' ') { | |
endIndex = j; | |
break; | |
} | |
} | |
for(let k = startIndex; k <= endIndex; k++) { | |
trimmed += s[k]; | |
} | |
return trimmed; | |
} | |
try { | |
const isNotNumber = function isNotNumber(value) { | |
return value !== null && (value != value || +value != value); | |
} | |
return !isNotNumber(trim(s)); | |
} catch (e) { | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment