Improving the Roman Numeral Kata with JavaScript

As a newcomer to the world of coding, I have taken on the challenge of mastering the Roman Numeral Kata using Javascript. I am pleased to report that all the specifications are passing successfully. After refactoring the spec file, I am now focusing on refactoring the main file.

This is what the code used to look like:

function roman(number) {
  var conversion = ''

  if (number == 100){
    conversion += 'C'
    number -= 100
  }
// omitted code

  while (number >= 1){
   conversion += 'I'
   number -= 1
 }

return conversion
}

After refactoring, the code looks like this:

function roman(number) {

  var denominations = {

    100: 'C',
    // omitted code
    5: 'V',
    4: 'IV',
    1: 'I'

  }

  var conversions = ''

  _.each(denominations, function(roman_num, natural_num) {
    while (number >= natural_num){ 
      conversions = conversions + roman_num
      number -= natural_num
    }
  })
  return conversions
}

I have been troubleshooting using the JS console in Chrome and it seems that instead of iterating through each denomination, the code keeps getting stuck at 1.

Furthermore, since I am using Jasmine, the error messages I see are as follows:

Expected 'IIII' to equal 'IV'
Expected 'IIIII' to equal 'V'

And so forth.

My current questions are: 1. Why does the code only return values for 1, 'I', and how can I resolve this issue? 2. What steps should I take to fix this particular problem?

Thank you in advance!

Answer №1

In JavaScript, objects are like HashMaps with strings as indices. Therefore, the order of elements in your "_.each" function may not be guaranteed to be the same as declared. It is advisable to use a structure that guarantees the order, such as an Array.

function roman(number) {
  var denominations_natural = [100, 5, 4, 1];
  var denominations_roman = ["C", "V", "IV", "I"];

  var conversions = '';

  for (var i=0; i<denominations_natural.length; i++) {
    while (number >= denominations_natural[i]) {
      conversions += denominations_roman[i];
      number -= denominations_natural[i];
    }
  }

  return conversions;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access property 'fetch' of null (discord.js)

Hey there, I'm running into an issue where it's giving me an error saying that the property 'fetch' doesn't exist. I'm using the Replit database for a balance command in discord.js. You can see the error image here. Here is t ...

"Enhance User Experience with Material UI Autocomplete feature that allows for multiple

I am encountering an issue with a material ui auto component that I am currently working on. The component's code looks like this: <Autocomplete multiple options={props.cats} defaultValue={editRequest? ...

Incorporate JavaScript functionality with HTML dropdown lists

I am attempting to achieve the following: The user can choose between "Option One" or "Option Two". If they select "Option One", the result will be 66 + 45, and if they select "Option Two", the result will be 35 + 45. How can I make this work using a com ...

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

Making an Axios request with parameters

I am facing an issue where my parameter articleid is not being passed to the route /createAnswer. When I log articleData._id, it shows the correct ID (e.g., 60b4f5d8c8be1d4cb0cdd6ca) that I want to pass to the route /createAnswer. const createAnswer = () = ...

Utilize filtering techniques on a nested system

After creating an Angular app to display a hierarchy, I am now attempting to add a text box on top of the hierarchy for data filtering purposes. Despite trying various filter examples, I have not achieved much success. My goal is to implement Angular bind ...

Using lambda expressions to sort through an array of objects in React

My goal is to create a delete button that removes items from a list and updates the state variable accordingly. public OnDeleteClick = (): void => { const selectionCount = this._selection.getSelectedCount(); let newArray = this.state.items; for ...

Troubles arise when hovering over and connecting endpoints in jsPlumb

I'm currently facing two challenges with my project. Follow this link for more details. 1) The hover effect is working perfectly on the endpoints, but I can't seem to change the colors of my connector when hovering over it. Any suggestions? (Ref ...

Vue.js Components Facing Build Issues

I am currently experiencing a puzzling phenomenon. While working on my application components using Laravel Jetstream and Inertia Stack with VueJS, I encountered an issue where a newly created component in the same folder as others was not building. Neithe ...

Generate a dynamic add to cart section for every last configurable choice, assisting with this task

Currently, I am involved in a project that involves displaying configurable options on a product page, along with querying the database to check which vendors carry the product. The list of vendors is then displayed using JavaScript. In order to make the ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

A new marker has been created on the Ajax Google Map, however, the old marker is still displaying as

Hey, I'm currently working on retrieving marker latitudes and longitudes using Ajax. I am receiving Ajax data every second and successfully creating markers within a specific radius. However, I'm running into an issue with updating marker positio ...

Experience the enhanced features and optimized performance of Onsen 2.0 compared to the earlier version

Apologies if this question is too simplistic, but I am finding some conflicting information in the documentation about using Onsen with Monaca. I am currently utilizing Monaca cloud and I prefer to work solely with pure JS, without incorporating Angular ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

Connecting factors

Let me simplify what my code does: var list = { "group":{ "subgroup1":[{"name1":"Jimmy","name2":"Bob"}], "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}] } } function group(group,name){ var link ...

Efficient method for managing complex JSON object updates using setState in React

My task involves handling structured data in JSON format, which I am unable to modify due to API restrictions. The challenge is to update the JSON file based on user modifications. { "id": 1269, "name": "Fet", &quo ...

What is the best way to include an icon before each option in a VuetifyJS combobox?

I'm looking to enhance the combobox feature in VuetifyJS by adding an icon before each option in the dropdown menu. Can someone guide me on how to achieve this functionality? You can check out a sample of the combobox on CodePen here: https://codepen. ...

Redirecting CORS in Cordova: A Comprehensive Guide

My Cordova/Phonegap app is encountering an issue while trying to retrieve certain files using AJAX. The specific error message that I receive states: XMLHttpRequest cannot load https://docs.google.com/uc?export=open&id=.... Redirect from 'https ...

Transmit and receive information between Javascript and Node.js through Express framework

Currently, I am utilizing the Express platform along with the Twilio Node.js SMS API and JavaScript to send text messages to my users. However, I am facing an issue in sending data through GET variables on the front-end and capturing those values with node ...

Assist me in minimizing redundant code in a basic jQuery function

I successfully created a carousel using the jQuery cycle plugin with 4 links that correspond to different slides. Currently, I have separate blocks of code for each link, but I'm looking to optimize by creating a single function. $('#features-sl ...