Skip to content

Instantly share code, notes, and snippets.

@ramsunvtech
Created September 22, 2019 17:54
Show Gist options
  • Save ramsunvtech/654d6166fc45a2a20e80f89b005280d4 to your computer and use it in GitHub Desktop.
Save ramsunvtech/654d6166fc45a2a20e80f89b005280d4 to your computer and use it in GitHub Desktop.
isValidNumber.js
/*
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