Last active
July 20, 2020 22:23
-
-
Save Dimanaux/08ccf712e80505f90251a8295315ce98 to your computer and use it in GitHub Desktop.
parseInt() reloaded solution https://www.codewars.com/kata/525c7c5ab6aecef16e0001a5/train/javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// >= 0, <= 1_000_000 | |
// problem suggests that string can only contain 'million' | |
// or less -> million can occure only once and it's the whole string | |
const parseInt = (string) => | |
string.includes('million') | |
? 1000000 : parseMillion(string); | |
// < 1_000_000 | |
// if we have 'thousand' word in given string, | |
// split on it and solve parse left, multiply it by 1000 | |
// solve right part and sum | |
const parseMillion = (string) => { | |
if (string.includes('thousand')) { | |
let [left, right] = string.split('thousand'); | |
return parseThousand(left) * 1000 + parseThousand(right); | |
} | |
// if string has no 'thousand', it is less than 1000 | |
return parseThousand(string); | |
}; | |
// < 1_000 | |
// look parseMillion, the same logic | |
const parseThousand = (string) => { | |
if (string.includes('hundred')) { | |
let [left, right] = string.split('hundred'); | |
return parseHundred(left) * 100 + parseHundred(right); | |
} | |
return parseHundred(string); | |
}; | |
// < 100 | |
// split string on space and '-' | |
// delete empty words and 'and' words | |
// transalte words into integers and find its sum | |
const parseHundred = (string) => { | |
let words = string.split(/[\s-]/) | |
.filter(w => w !== '') | |
.filter(w => w !== 'and'); | |
return words.map(w => wordToInt[w]).reduce((x, acc) => acc + x, 0); | |
}; | |
// map words to significant integers | |
const wordToInt = { | |
zero: 0, 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, nineteen: 19, | |
twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, | |
eighty: 80, ninety: 90, | |
hundred: 100, thousand: 1000, million: 1000000 // these are unnecessary | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment