Created
August 10, 2022 19:50
-
-
Save ZakriaJanjua/e042597b66dde39d3d24adb60c90e880 to your computer and use it in GitHub Desktop.
codewars kata of parseInt.js 4kyu solution
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
function parseInt(string) { | |
// TODO: it's your task now | |
const dictionary = {"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}; | |
const multi = { | |
'hundred': 100, | |
'thousand': 1000, | |
'million': 1000000 | |
} | |
const words = string.split(/ |-/) | |
let duplicate_words = [...words] | |
let result = 0 | |
let prev = 0 | |
for (let i of words) { | |
if (dictionary[i]) { | |
result += dictionary[i] | |
prev += dictionary[i] | |
duplicate_words.shift() | |
} | |
else if (multi[i]) { | |
let multiplier = multi[i] | |
for (let j of duplicate_words) { | |
if (multi[j] > multiplier) { | |
multiplier = multiplier * multi[j] | |
break; | |
} | |
} | |
result += (prev * multiplier) - prev | |
prev = 0 | |
duplicate_words.shift() | |
} | |
} | |
return result | |
} | |
console.log(parseInt('twenty-six thousand three hundred fifty-nine')) | |
console.log(parseInt('six hundred sixty-six thousand six hundred sixty-six')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment