JavaScript - Roman Numeral Converter
It doesn't throw an error, but doesn't give correct output if the input is a number beginning with 0.
const ints = [ 015 ]; //Expected output: XV //Actual output: XIII
It appears ECMAScript treats this representation as an octal (base-8) number if all digits in the number are less than 8. Are there any rules governing what input you accept? Must the input always be a base-10 integer? It's obviously an edge case with a small chance of happening, but if someone accidentally strikes a zero (say with number pad entry) and gets this conversion, it would be confusing. You can trim leading zeros in a couple ways, first, you could convert the input to a string, then invoke parseInt, specifying decimal as the number base to use, then convert the output of that back to a string:
let strNum = parseInt(number.toString(), 10).toString();
Or, you could Regex away all zeroes at the beginning of the string:
let strNum = String(number); strNum = strNum.replace(/^0+/, '');
Should anything happen if the input isn't a Number type? Again, your function doesn't throw any errors, instead giving undefined output for this case:
const ints = [ 'XIII' ];
Attempting to sanitize weird user input is always something we need to do as programmers: "Garbage in, garbage out." Depending on requirements, code working, but not alerting the user to errant inputs might not be the desired outcome. For a beginner, the code is great, but a minor suggestion: personally, I'd prefer spaces instead of tabs for indentation. Tab sizes vary widely, spaces generally don't. And if you aren't consistent between tabbing or using spaces, the file might look fine in your editor, but if I'd copy it into mine, it would look awful. You can make sure your editor of choice inserts spaces instead of tabs using its text editor settings, wherever those live.
Also, I looked up the exponentiation operator on the MDN. While this overload enjoys wide support, it's not supported by older versions of browsers. If your "customer" would be using old hardware/software, the code wouldn't work (at all, or as expected, depending on platform-specific error handling). Platform support for what you write is also something to be cognizant of if you want to enter the industry as a professional.

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now