daily pastebin goal
46%
SHARE
TWEET

Untitled

a guest Jan 18th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // >= 0, <= 1_000_000
  2. // problem suggests that string can only contain 'million'
  3. // or less -> million can occure only once and it's the whole string
  4. const parseInt = (string) =>
  5.   string.includes('million')
  6.   ? 1000000 : parseMillion(string);
  7.  
  8. // < 1_000_000
  9. // if we have 'thousand' word in given string,
  10. // split on it and solve parse left, multiply it by 1000
  11. // solve right part and sum
  12. const parseMillion = (string) => {
  13.   if (string.includes('thousand')) {
  14.     let [left, right] = string.split('thousand');
  15.     return parseThousand(left) * 1000 + parseThousand(right);
  16.   }
  17.   // if string has no 'thousand', it is less than 1000
  18.   return parseThousand(string);
  19. };
  20.  
  21. // < 1_000
  22. // look parseMillion, the same logic
  23. const parseThousand = (string) => {
  24.   if (string.includes('hundred')) {
  25.     let [left, right] = string.split('hundred');
  26.     return parseHundred(left) * 100 + parseHundred(right);
  27.   }
  28.   return parseHundred(string);
  29. };
  30.  
  31. // < 100
  32. // split string on space and '-'
  33. // delete empty words and 'and' words
  34. // transalte words into integers and find its sum
  35. const parseHundred = (string) => {
  36.   let words = string.split(/[\s-]/)
  37.           .filter(w => w !== '')
  38.           .filter(w => w !== 'and');
  39.   return words.map(w => wordToInt[w]).reduce((x, acc) => acc + x, 0);
  40. };
  41.  
  42. // map words to significant integers
  43. const wordToInt = {
  44.   zero: 0, one: 1, two: 2, three: 3, four: 4,
  45.   five: 5, six: 6, seven: 7, eight: 8, nine: 9,
  46.   ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14,
  47.   fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19,
  48.   twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70,
  49.   eighty: 80, ninety: 90,
  50.   hundred: 100, thousand: 1000, million: 1000000 // these are unnecessary
  51. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top