I have a function that creates filters for some data. The filters get added to an array and then (later) chained through the reduce
function (the chaining part not part of my question).
The data I receive are all strings but can actually be numbers, eg {name:"-45.6"}
. If it can be a number, I want the value to be converted to a number.
formFilters = (builder) => {
const filters = [];
builder.forEach(b => {
let {filtername, operator, value} = b;
if(!value) return;
if(isNumber(value)){
value = Number(value);
}
switch (operator) {
case "=":
filters.push((item) => convertToNumber(item[filtername]) === value);
break;
case "<":
filters.push((item) => convertToNumber(item[filtername]) < value);
break;
case ">":
filters.push((item) => convertToNumber(item[filtername]) > value);
}
});
return filters;
}
function convertToNumber(value){
const number = Number(value);
if (!Number.isNaN(number)) return number;
return value;
}
This works but I'm wondering if there's a cleaner way of converting the value to a number if it is a number?
1 Answer 1
One problem with Number(value);
is that it casts falsy values as 0
and truthy values as 1
.
That means that an empty string becomes 0
, which may not be what you expect.
You could make a regular expression test on the input to determine if it fits your expectations for a number.
let input = document.getElementById('input');
let result = document.getElementById('result');
function IsANumber() {
let isItANumber = input.value.match(/^-?\d*\.?\d+$/);
result.innerHTML = isItANumber ? 'true' : 'false';
}
<input id="input" onchange="IsANumber()" onkeyup="IsANumber()" /><br/> Is a number: <span id="result"></span>
The example above will not fail in truthy/falsy cases, but it will determine strings like "Infinity" to not be numbers too. Therefore it may need to be modified if you have to parse these to numeric values.
-
1\$\begingroup\$ The function will fail for numbers like
"1e2"
,"0x10"
,"0b00"
returning false. \$\endgroup\$Blindman67– Blindman672021年03月26日 09:56:43 +00:00Commented Mar 26, 2021 at 9:56
const convertToNumber = value => isNaN(value) ? value : Number(value);
\$\endgroup\$