0

For example, I have user input any string: "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. These are just examples, the user can input any string.

I want to map this to integer cardinality:

"1st" -> 0
"2nd" -> 1
"third" -> 2
"fourth" -> 3
"fifth" -> 4
"9999th" -> 9998

So I need some kind of function where:

   function mapCardinality(input: string): number{
     let numberResult:number = ??
     return numberREesult;
   }

and I can call it like this:

console.log(
  mapCardinality("1st"), // print 0
  mapCardinality("2nd"), // print 1
  mapCardinality("third"), // print 2
  mapCardinality("fourth"), // print 3
  mapCardinality("fifth"), // print 4
  mapCardinality("9999th") // print 9998
);
Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174

2 Answers2

0

Just look it up in an array or parse it as number:

const mapCardinality = c => {
   const pos = ["1st", "2nd", "third", "fourth",  "fifth"].indexOf(c);
   return pos === -1 ? parseInt(c, 10) - 1 : pos;
};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

I'd first ask what are the suffixes for all of the inputs?

  • 'nd', 'rd', 'st', 'th' (most numbers)

If they enter an integer with the above prefixes then you could write the following function:

const getInteger = input => input.slice(0, -2);
const num = getInteger('999th');
console.log(num); // prints "999"

If they enter the elongated variant, it becomes much more complex, especially when it comes to typos, lack of spaces, etc. One way could be to map single digit words ('one', 'two', etc), tens ('ten', 'twenty', etc'), hundreds, thousands, and so on instead of every number imaginable. I would then parse and find matching words to give a result. That being said it is still limiting. I would strongly suggest limiting user input formats. Why can't the user input an integer?

const cardinalDictionary = {
  'zero': 0,
  'one': 1,
  ...,
  'twenty',
  ...,
  'hundred': 100,
  'thousand': 1000,
};
Ross Sheppard
  • 850
  • 1
  • 6
  • 14