What is the process for triggering an exception?

I have a specific function that converts a two-dimensional array into CSV format. The key requirement is that the function only supports text and numbers, triggering an error message for any other input types. Currently, when I execute the function, it stops working at the first incompatible input encountered. How can I modify the function to handle such situations and continue processing the rest of the array?

function arraysToCsv(data) {
  for(let i = 0; i < data.length; i++){
    let value = data[i];
    for(let j = 0; j < value.length; j++){
      if(typeof value[j] !== 'string' || typeof value[j] !== 'number')
        throw new Error('Unexpected value');
      let result = value[j].replace(/"/g, '""');
      if (result.search(/("|,|\n)/g) >= 0){
          result = '"' + result + '"';
      }
      return result.join(',') + '\n';
  }
  }
}

Answer №1

To ensure that your function only operates on either numbers or strings, include a continue statement within the if condition checking the type of the value.

if(typeof value[j] !== 'string' || typeof value[j] !== 'number') continue;

If you need to display an error message, you can utilize alert or write it to the console using console.log before the continue statement. I hope this information proves helpful to you.

Answer №2

function convertArraysToCsv(data) {
  for(let i = 0; i < data.length; i++){
    let value = data[i];
    for(let j = 0; j < value.length; j++){
      let typeOfValue = typeof(value[j]);
      let isStringOrNumber = typeOfValue === 'string' || typeOfValue === 'number';
      if(!isStringOrNumber)
        throw new Error('Unexpected value');
      let result = value[j].replace(/"/g, '""');
      if (result.search(/("|,|\n)/g) >= 0){
          result = '"' + result + '"';
      }
      return result.join(',') + '\n';
  }
  }
}

Otherwise (employ and)...

function convertArraysToCsvData(data) {
  for(let i = 0; i < data.length; i++){
    let value = data[i];
    for(let j = 0; j < value.length; j++){
      let typeOfValue = typeof(value[j]);
      let isNotStringOrNumber = typeOfValue !== 'string' && typeOfValue !== 'number';
      if(isNotStringOrNumber)
        throw new Error('Unexpected value');
      let result = value[j].replace(/"/g, '""');
      if (result.search(/("|,|\n)/g) >= 0){
          result = '"' + result + '"';
      }
      return result.join(',') + '\n';
  }
  }
}

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

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Utilizing DataTables and Ajax call to refresh table data with Json response

My table is dynamically generated using Thymeleaf and I want to update its contents with jQuery. <table class="table table-hover" id="main-table"> <thead class="thead-inverse"> <tr> <th class="c ...

Incrementing values in ng-repeat object automatically

My project involves extracting game information from mlb.com and utilizing angularjs along with the ng-repeat directive to display it. A sample of the JSON feed is shown below. { "data": { "games": { "next_day_date": "2017-08-19", "mo ...

When working with React Native, encountering an issue where passing props using the Map function results in an error stating "undefined is not a function" near the section of code involving the

Hey there! I'm currently facing an issue with fetching data from my Sanity CMS and passing it as props to a child component. Interestingly, the same code worked perfectly on another screen, but here I seem to be encountering an error. Although the dat ...

Transferring MongoDB information to a Jade template in an ExpressJS application

Hey there, hoping you can assist me with a query issue I'm facing. To give you some context, I am querying a MongoDB collection and trying to pass the results back to a Jade view. app.helpers({ clients: function(){ users.find({uid:req.session.u ...

The static files are being received by Django but are not functioning properly

I've been working on a project using django 1.7, and below is my settings.py configuration: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) STATIC_ROOT = "absolute/path/to/static" In the 'assets&apo ...

What causes a never-ending loading cycle on a website when a 404 error occurs?

My Express.js/Node.js website is hosted on Heroku. I am facing an issue where the server does not properly send a 404 error when a file cannot be found. Instead, the page keeps loading endlessly. How can I make the server stop loading when it encounters a ...

Ways to conceal an animated gif once it has been downloaded?

Is it possible to have an animated gif image vanish once server-side Java code runs and the client receives an HTTP Response from the webserver without relying on Ajax? I am currently utilizing the following Struts2 submit button: <s:submit value="sho ...

Iterate through the entire array without including a specific item

I am struggling with looping through an array of items and applying some code to each item while excluding one specific item (the clicked-on item). I have experimented with using splice, but that method ends up removing the array item completely, whereas I ...

Remove feature in HTML file upload form

I have a basic upload form set up like this: <form method="post" action="" enctype="multipart/form-data"> <table border="0"> <tr> <td>Select XML file to upload ...

What is the way to display the final list item when clicking in jQuery?

I am attempting to achieve a specific behavior where clicking on a button will trigger the content below to scroll in such a way that only the last item in the list is visible. I have been using jQuery for this functionality, but unfortunately, it is not ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

Tips for developing a versatile code for passport.authenticate

I have a scenario where multiple controllers contain various methods that require user authentication to access database data. I am currently attempting to streamline the authentication process to avoid repetition in my code. Within the controller: const ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

- "Queries about Javascript answered with a drop-down twist

Having some trouble with setting up a straightforward FAQ dropdown feature. Could someone lend a hand and see what might be going wrong? Appreciate your help! CSS #faqs h3 { cursor:pointer; } #faqs h3.active { color:#d74646; } #faqs div { height:0; o ...

Efficiently organizing reducers into separate files in ReactJS and merging them together

My App is a simple counter app where buttons are images with their own counters. https://i.stack.imgur.com/qkjoi.png In my App.js file, I imported the reducer for the counters using the following code: import reducer from './reducers/reducerCounter&a ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

Quickly switch between pages as they load

In Chrome, I'm experiencing a white flash between page loads that is causing transitions to appear choppy. I've taken various steps to optimize the site, such as using image sprites, reducing image sizes, minifying CSS, ensuring correct CSS loadi ...

Using a toolbar to insert a hyperlink for hypertext communication

My journey with Javascript and React began this week, so I'm still getting the hang of things, especially in the front end domain. In my project, there's a link button within a toolbar. The idea is to click on it, have a text box pop up where yo ...

Error: Unable to access property 'BOTTOM' of an object that is not defined

Hi there, I'm having trouble with this error. Can you assist me? [ERROR] TiExceptionHandler: (main) [340,3234] /ui/common/ApplicationTabGroup_Andr.js:1703 [ERROR] TiExceptionHandler: MainWallTable.insertRowBefore([0, PendingUploadView, T ...