Last active
June 2, 2017 06:39
-
-
Save AnastasiaDunbar/8fb2039d297bffd1f8463825f4d4e7b6 to your computer and use it in GitHub Desktop.
Ord till nummer (eller tal, jag vet inte och vem fan bryr sig). https://stackoverflow.com/a/12014376/4538129
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
var small={ | |
"noll":0, | |
"ett":1, //Only idiots say "en" as a number. | |
"två":2, | |
"tre":3, | |
"fyra":4, | |
"fem":5, | |
"sex":6, | |
"sju":7, | |
"åtta":8, | |
"nio":9, | |
"tio":10, | |
"elva":11, | |
"tolv":12, | |
"tretton":13, | |
"fjorton":14, | |
"femton":15, | |
"sexton":16, | |
"sjutton":17, | |
"arton":18, | |
"nitton":19, | |
"tjugo":20, | |
"trettio":30, | |
"fyrtio":40, | |
"femtio":50, | |
"sextio":60, | |
"sjuttio":70, | |
"åttio":80, | |
"nittio":90 | |
},magnitude={ | |
"tusen" :1000, | |
"miljon" :1000000, | |
"biljon" :1000000000, | |
"triljon" :1000000000000, | |
"kvadriljon":1000000000000000, | |
"kvintiljon":1000000000000000000, | |
//There's something wrong with you if you need bigger numbers. | |
}; | |
function text2num(string){ | |
var array=string.toString().split(/[\s-]+/),n=0,g=0,keys=Object.keys(small).concat("hundra",Object.keys(magnitude)).sort((a,b)=>b.length-a.length); | |
for(var i=0;i<array.length;i++){ | |
if(keys.indexOf(array[i])==-1){ | |
var mergedWord=array[i],newArray=[],atChar=0; | |
while(atChar<mergedWord.length){ | |
var found=false; | |
for(var j=0;j<keys.length;j++){ | |
if(mergedWord.substr(atChar,keys[j].length)==keys[j]){ | |
newArray.push(keys[j]); | |
atChar+=keys[j].length; | |
found=true; | |
break; | |
} | |
} | |
if(!found){ | |
alert("Kan inte dela: "+mergedWord.substr(atChar)); | |
break; | |
} | |
} | |
if(found){ | |
array.splice(i,1,...newArray); | |
} | |
} | |
} | |
array.forEach((word)=>{ | |
var x=small[word]; | |
if(x!=null){ | |
g+=x; | |
}else if(word=="hundra"){ //You must say "ett hundra" instead of "hundra" if you want 100. | |
g*=100; | |
}else{ | |
x=magnitude[word]; | |
if(x!=null){ | |
n=n+g*x; | |
g=0; | |
}else{ | |
alert("Okänt nummer: "+word); | |
} | |
} | |
}); | |
return n+g; | |
} | |
//console.log(text2num("etthundratjugotretusen")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment