Reputation: 367
I have an array of number suffixes in order of how big they are:
[0] = 0 - 999 ("")
[1] = 1,000 - 999,999 ("k")
[2] = 1,000,000 - 999,999,999 ("M")
[3+] = etc.
And I want to write a function to check if a string is a valid number with one of these suffixes at the end, and then return either a valid number with the suffix removed (1.57k
to 1570
) or false
if the input string can't be converted to a number.
I already have a working version for this, but it's messy and slow and I was unable to figure out how to improve it.
Note: Some of the prefixes start with another prefix, for example, T and TrD or Qa and QaD. And I'd want to always match the full one, not just the first one found.
Edit: The array of possible suffixes can/will change.
Upvotes: 1
Views: 278
Reputation: 2285
I'm taking care of "check if a string is a valid number with a suffix". You will just have to add your calculation function using this given result.
function getSuffix(input){
const [ suffix ] = input.match(/[^\d]+$/) || [];
return suffix;
}
function suffixIsValid(suffix){
if(!suffix){
return false;
}
const suffixes = ["k", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc", "UnD", "DuD", "TrD", "QaD", "QiD", "SeD", "SpD", "OcD", "NoD", "Vi", "UnV"];
return suffixes.some(validSuffix => validSuffix.toLowerCase() === suffix.toLowerCase());
}
function isValidNumberWithValidSuffix(input){
const number = parseFloat(input);
const suffix = getSuffix(input);
return !isNaN(number) && (!suffix || (suffix && suffixIsValid(suffix))) ? { number, suffix } : false;
}
console.log(isValidNumberWithValidSuffix(("InvalidNumber")));
console.log(isValidNumberWithValidSuffix(("153InvalidSuffix")));
console.log(isValidNumberWithValidSuffix(("153")));
console.log(isValidNumberWithValidSuffix(("15.3M")));
console.log(isValidNumberWithValidSuffix(("1.53qad")));
Upvotes: 1