Last active
February 25, 2017 11:03
-
-
Save ostapenko-me/dce032d74d08586a5c2c3433bcc43c2c to your computer and use it in GitHub Desktop.
One line JavaScript fromRoman function
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 assert = require('assert'); | |
| const numbersDict = { | |
| I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 | |
| }; | |
| const fromRoman = input => [...input.toUpperCase()].reduce((number, letter, i, source) => number + (numbersDict[letter] >= ( numbersDict[source[i + 1]] | 0)) ? numbersDict[letter] : -numbersDict[letter], 0); | |
| assert.equal(fromRoman('I'), 1, 'I=' + fromRoman('I')); | |
| assert.equal(fromRoman('XI'), 11, 'XI=' + fromRoman('XI')); | |
| assert.equal(fromRoman('XXI'), 21, 'XXI=' + fromRoman('XXI')); | |
| assert.equal(fromRoman('XXVI'), 26, 'XXVI=' + fromRoman('XXVI')); | |
| assert.equal(fromRoman('MMMD'), 3500, 'MMMD=' + fromRoman('MMMD')); | |
| assert.equal(fromRoman('XIX'), 19, 'XIX=' + fromRoman('XIX')); | |
| assert.equal(fromRoman('IV'), 4, 'IV=' + fromRoman('IV')); | |
| assert.equal(fromRoman('IX'), 9, 'IX=' + fromRoman('IX')); | |
| assert.equal(fromRoman('MMCD'), 2400, 'MMCD=' + fromRoman('MMCD')); | |
| assert.equal(fromRoman('MMCM'), 2900, 'MMCM=' + fromRoman('MMCM')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment