Created
June 6, 2016 16:22
-
-
Save octopitus/6b9804eaa14776aa69ddc0355a205cdd to your computer and use it in GitHub Desktop.
convert English phrase to integer
This file contains hidden or 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
const splitChars = /\b(billion|million|thoudsand|hundred)s?/g | |
const points = { | |
billion: 1000000000, | |
million: 1000000, | |
thoudsand: 1000, | |
hundred: 100 | |
} | |
const digits = { | |
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 | |
} | |
function integerFromEnglishPhrase(str) { | |
let value = 0 | |
const localPoints = [], localDigits = [] | |
str = str.split(splitChars) | |
str.forEach((value, index) => { | |
value = value.trim() | |
if (value in points) { | |
localPoints.push(points[value]) | |
return | |
} | |
if (value !== '') { | |
localDigits.push(value.split(' ').reduce((a, b) => a + digits[b], 0)) | |
} | |
}) | |
const totalDigits = Math.max(localPoints.length, localDigits.length) | |
let result = 0 | |
for (var i = 0; i < totalDigits; i++) { | |
if (localDigits[i]) { | |
result = result + localDigits[i] * (localPoints[i] || 1) | |
} else if (localPoints[i]) { | |
result = result * localPoints[i] | |
} | |
} | |
if (result > Number.MAX_VALUE) { | |
return Infinity | |
} | |
return result | |
} |
This file contains hidden or 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
integerFromEnglishPhrase('one thoudsand two hundred thirty four') // 1234 | |
integerFromEnglishPhrase('one thoudsand two hundred') // 1200 | |
integerFromEnglishPhrase('thirty four') // 34 | |
integerFromEnglishPhrase('one thoudsand billions') // 1000000000000 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment