Skip to content

Instantly share code, notes, and snippets.

@taylorlapeyre
Last active May 28, 2019 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taylorlapeyre/50fb4c8b0e7329a1c3d2a4873d259d90 to your computer and use it in GitHub Desktop.
Save taylorlapeyre/50fb4c8b0e7329a1c3d2a4873d259d90 to your computer and use it in GitHub Desktop.
const dictionary = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"ninetine": 19,
"twenty": 20,
"thirty": 30,
"fourty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninty": 90,
};
const placeModifiers = {
"hundred": 100,
"thousand": 1000,
"million": 1000000
}
function isValidNumberWord(maybeNumberWord) {
return (maybeNumberWord in dictionary) || (maybeNumberWord in placeModifiers);
}
function translateNumberSentence(numberSentence) {
const words = numberSentence.split(" ");
if (words.some(word => !isValidNumberWord(word))) {
throw new Error("Invalid number sentence.");
}
if (words.length === 1) {
return translateNumberWord(words[0]);
}
let sum = 0;
for (let i = 0; i < words.length; i++) {
const word = word[i];
if (word in placeModifiers) {
const previousWord = words[i - 1];
if (previousWord in placeModifiers) {
sum *= placeModifiers[word]; // multiply the sum by the place modifier
} else {
sum -= dictionary[previousWord]; // remove the single digit we just erroneously added
sum += dictionary[previousWord] * placeModifiers[word]; // add the modifier
}
} else {
sum += dictionary[word];
}
}
return sum;
}
console.log(translateNumberSentence("one hundred thousand fourty two"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment