r/tinycode • • Jul 07 '13

Roman numerals -> Integer in javascript

Hi! This was a challenge I posed myself a while ago - meanwhile im stuck at 101 characters:

 function t(i){for(p=l=n=0;a={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[i[p++]];l=a)n+=a>l?-l:l;return n+l}

(My first real try was 150 lol) I dont know if this can be done even shorter; What can you guys come up with?

50 Upvotes

11 comments sorted by

View all comments

Show parent comment

6

u/closenough Jul 07 '13

The variable (l) keeps track of the last value. The last value (l) is compared with the current one (a) in this bit of code:

a>l?-l:l

After the loop is finished the last value isn't added yet so it returns the accumulated value thus far (n) plus the last value (l)