Struggling with Typescript switch/case not correctly matching strings as expected

I encountered an unusual issue with a switch statement designed to handle different values of a string.

While working on a parser and utilizing TDD, I successfully created and tested a function that parses individual lines accurately for all scenarios.

My current task involves developing a larger function capable of parsing multiple lines at once. This new function essentially divides the input into separate lines and then calls the single-line parsing function.

The problem arises during value checking:

parseLine(terrainLine: string): Terrain | Tile[] | Adventurer {
    const [lineType, ...lineData] = terrainLine.trim().split(' - ');

    switch (lineType) {
      case 'C':
        return Terrain.parseTerrain(lineData);

      case 'T':
        return Terrain.parseTreasures(lineData);

      case 'M':
        return [Terrain.parseMountain(lineData)];

      case 'A':
        return Terrain.parseAdventurer(lineData);

      default: {
        throw new TerrainError(
          `Unable to parse terrain tile with data: "${terrainLine}"`,
        );
      }
    }
  }

Although this function is thoroughly tested and functions correctly with strings like 'C - 3 - 4', it encounters issues when invoked by the following function, triggering the default case instead:

parse(terrainString: stirng): Terrain {
  const linesToParse = terrainString
      .split('\n')
      .map((_) => _.trim()) // Remove leading and trailing spaces
      .filter((_) => _.length && !_.startsWith('#')); // Exclude empty and comment lines

  linesToParse.forEach((line) => {
      const parsed = Terrain.parseLine(line);
      // [...]
  }  

  // [...]
}

Here are the test cases for reference:

// Successful test
it('should parse terrain lines right', () => {
  const terrainLine = 'C - 3 - 4';
  const expectedTerrain = new Terrain(3, 4);
  const parsed = parseLine(terrainLine);

  expect(parsed).toBeInstanceOf(Terrain);
  expect(parsed).toStrictEqual(expectedTerrain);
});

// Unsuccessful test
it('should accept valid terrains', () => {
  const terrainString = 'C​ - 3 - 4\nM​ - 1 - 0\nM​ - 2 - 1\nT​ - 0 - 3 - 2\nT​ - 1 - 3 - 3\nA​ - Lara - 1 - 1 - S - AADADAGGA\n';

  expect(() => {
    Terrain.parse(terrainString);
  }).not.toThrow();
});

Answer №1

Highlighted by @VLAZ, I encountered a hidden zero-width character within my string that triggered the issue. By eliminating this character from the string, the problem was successfully resolved.

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

Leveraging Bootstrap grids with JavaScript

$.getJSON('http://localhost/REST_API/api/post/read.php', function(data) { var count = 0; data.forEach(obj => { if(count % 3 === 0) { $( ".monsterlist" ).append("<div class='row'>" ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

Tips for updating the appearance of a ListItem with a click action

For my current project, I am using Material UI and React. One of my components is structured as follows: import React, { Component } from 'react'; import { List, ListItem } from 'material-ui'; import PropTypes from 'prop-types&apo ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

What steps can I take to ensure that AstroJS components do not conceal SVG elements when the SVG is incorporated into another file with client:load?

Currently, I am developing a weather application using Astro.js in conjunction with React. One of the features includes an SVG component that serves as the project logo and is implemented in the initial page loader. Upon the page loading, the SVG functions ...

In VueJS 3, the data within the app.component instance will lack reactivity if it is declared within the data() or setup() functions

When it comes to declaring new reactive variables inside a component, I faced an interesting issue. It seems that setting the component globally, outside the app.component instance, and then returning it to either the data() or setup() function works perfe ...

Adjust the dimensions of the ng2-charts to fit your needs

Is there a way to specify the width and height of a chart using ng2-charts? Specifically, I am working on a Bar chart similar to the one shown in the ng2-charts demo. public doughnutChartLabels:string[] = ['EMI', 'Car', 'Food&apos ...

Using ASP.NET Server Controls to Toggle Textbox Visibility Based on Dropdown Selection

What is the optimal method for displaying or hiding a textbox or an entire div section based on a user's selection from a dropdown menu? I am uncertain if this can be achieved with server controls, so would it require using standard client-side HTML c ...

Issue with Date Picker not properly storing selected date in MySQL database

My goal is to save the datepicker date to MySQL by selecting the date format using JavaScript. I have verified that the date format appears correct as YYYY-MM-DD when logging to the console. However, when I try to execute an INSERT query to MySQL, the date ...

javascript for transforming date format

My textfield is set to be a date field with a jQuery datepicker(). The dateFormat() is dd-mm-yy, which works perfectly. However, MySQL requires dates to be in yyyy-mm-dd format. I am wondering if I can convert the date format using PHP or JavaScript before ...

Increase and decrease buttons using the 'keydown' event (ArrowUp and ArrowDown)

I'm seeking assistance with a school project. I currently have two buttons, one for incrementing and one for decrementing. There are four functions in total, two for clicking and two for using arrow keys. The clicking functionality works fine, but whe ...

Displaying the order number in an alert notification once the form has been successfully submitted and retrieved from the database

After successfully displaying an alert box message confirming that my form has been submitted, I now want to enhance it by adding the order number retrieved from my database. The current code snippet in my PHP script displays a basic alert as shown below: ...

Switching Image Values in JavaScript: A Quick Guide

After successfully using a JavaScript function to swap the src of two images, I encountered an issue. I also needed to switch two values associated with the images so that I could calculate them later. For example: img src="ble.jpg" id="F" value="" onclic ...

Countless unsuccessful connection attempts on Node.js and socket.io

Good day awesome community at SO! I've been struggling to resolve this issue, and now I'm turning to you for some guidance because I can't seem to figure it out on my own. I have a node.js server that serves an index.html through express, an ...

How to manage UNC paths and "mapped network drives" within an Electron application?

I have developed a cross-platform (macOS-Windows) app using Electron that functions smoothly with files and media assets from a local drive. However, it encounters issues when dealing with UNC paths and "mapped network drives". Since I am a contractor, I d ...

Error caused by external Javascript and CSS files blocking the rendering process

Having encountered an issue, I find myself grappling with numerous external blocking rendering errors, as evident from this report: https://developers.google.com/speed/pagespeed/insights/?url=antsmarching.com.au&tab=desktop I put forth my best efforts ...

I'm experiencing some strange symbols on my page that look like ''. It appears to be a problem occurring between the servlet and the Javascript. How can I resolve this issue?

After retrieving a CSV file from my servlet, I noticed that characters like 'é', 'á' or 'õ' are not displaying properly on my page. Strangely, when I access the servlet directly via browser, everything appears fine. I atte ...

What is the best way to trigger a refresh of a cached CSS file on a JSP website, without using PHP?

I am currently making significant changes to my site by modifying a CSS file. Is there a way to compel clients to refresh the CSS in order to see the new updates? Unfortunately, it is not feasible to ask thousands of people to manually reload the page us ...