I have this function
this function has to detect numeric and nonnumeric numbers like ‘one’ or ‘1’;
but the trickiest part is when when you have something like ‘twone‘ in there you have both ‘one’ and ‘two’, and o is common for solving this problem.
I decided not to increase the pointer ‘i’ to keep the last word and check again that is there any numbers starts with ‘o’,
but in this case ‘twothree’; it fails.
because you keep ‘o’ and but the next letter is ‘t’ and there is no numbers starts with ‘ot’,
So in this case I need to increase pointer ‘i’ because I have ‘three’
this is my code
function detectNumbers(input) {
const wordToNumbers = new Map([
['zero', '0'],
['one', '1'],
['two', '2'],
['three', '3'],
['four', '4'],
['five', '5'],
['six', '6'],
['seven', '7'],
['eight', '8'],
['nine', '9']
]);
let outStr = '';
let myStr = '';
let i = 0;
while (i < input.length) {
if (!isNaN(Number(input[i]))) {
myStr = ''; // Reset myStr if the character is a number
outStr += input[i];
i++;
} else {
myStr += input[i];
let keyFound = false;
for (const key of wordToNumbers.keys()) {
if (key.startsWith(myStr)) {
keyFound = true; // Set flag to true if a key is found
i++;
if (wordToNumbers.has(myStr)) {
outStr += wordToNumbers.get(myStr);
myStr = '';
i--;
break; // Exit the loop after finding a word and getting a number
}else break;
}
}
if (!keyFound) {
myStr = ''; // Reset myStr if no key is found
i++;
}
}
}
const result = outStr.length > 0 ? outStr[0] + outStr[outStr.length - 1] : outStr[0] + outStr[0];
return parseFloat(result);
}
detectNumbers('eightwothree')
3
Answers
}
detectNumbers(‘8oneightwone’);
Another approach is checking all words inside the string and then sorting them by index:
Build a tree of characters for numbers and walk through it: