Last active
August 29, 2015 14:08
-
-
Save blasten/b370c3bf2090202fd57e to your computer and use it in GitHub Desktop.
Converts words to a decimal value. e.g. one thousand five hundred fifty two and five cents = 1552.05
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 getValue(str) { | |
switch (str) { | |
case 'one': | |
return 1; | |
case 'two': | |
return 2; | |
case 'three': | |
return 3; | |
case 'four': | |
return 4; | |
case 'five': | |
return 5; | |
case 'fifty': | |
return 50; | |
} | |
return false; | |
} | |
function getMagnitude(str) { | |
switch (str) { | |
case 'thousand': | |
return 1000; | |
case 'hundred': | |
return 100; | |
case 'cents': | |
return 0.01; | |
} | |
return false; | |
} | |
function getDecimal(str) { | |
var words = str.toLowerCase().split(' '); | |
var decimal = 0; | |
var NO_VALUE = -1; | |
var currentVal = NO_VALUE; | |
for (var i = 0; i < words.length; i++) { | |
var value = getValue(words[i]); | |
if (value !== false) { | |
if (currentVal == NO_VALUE) { | |
currentVal = value; | |
} else { | |
currentVal = currentVal + value; | |
} | |
} else { | |
var magnitude = getMagnitude(words[i]); | |
if (currentVal !== NO_VALUE) { | |
if (magnitude !== false) { | |
currentVal = currentVal * magnitude | |
} | |
decimal += currentVal; | |
currentVal = NO_VALUE; | |
} | |
} | |
} | |
if (currentVal !== NO_VALUE) { | |
decimal += currentVal; | |
} | |
return decimal; | |
} | |
// sample run | |
getDecimal("one thousand five hundred fifty two and five cents") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment