A Typescript function that can process either a single string or a collection of strings as its input

Here is a function that requires 2 arguments: a mandatory tableName and an optional connectionName:

export const clearTable = async (
  tableName: string[],
  connectionName = 'default'
) => {
  try {
    const connection = getConnection(connectionName)
    const promises = tableName.map((table) =>
      connection.query(`DELETE FROM ${table}`)
    )
    await Promise.all(promises)
  } catch (error) {
    throw new Error(
      `Failed to clear table '${tableName}' on database '${connectionName}': ${error}`
    )
  }
}

To use this function, you can call it like this:

clearTable(['table1', 'table2']) // works fine with an array
clearTable('table3') // fails because it's not an array > TypeError: tableName.map is not a function

If you need to convert a single string to an array of strings in order to use the same logic with array.map, one suggestion is to explore the possibility of utilizing rest parameters. However, be aware that a rest parameter can be zero or more, while we require at least one argument.

How would you handle this scenario efficiently?

Answer №1

Start by updating the parameter type from string[] to string[] | string. Then, within the try block, ensure that when you assign a value to promises, include a type check as follows: Array.isArray(tableName).

export const clearTable = async (
  tableName: string[] | string,
  connectionName = 'default'
) => {
  try {
    const connection = getConnection(connectionName)
    const promises = Array.isArray(tableName) ?
      tableName.map((table) => connection.query(`DELETE FROM ${table}`))
      :
      connection.query(`DELETE FROM ${tableName}`))
    await Promise.all(promises)
  } catch (error) {
    throw new Error(
      `Failed to clear table '${tableName}' on database '${connectionName}': ${error}`
    )
  }
}

Answer №2

To simplify the string | string[] => string[] issue into a single function, you can create the following code snippet and reuse it wherever needed:

const transformString = (input: string | string[]): string[] => {
  return typeof input === 'string'
    ? [input]
    : input;
}

Answer №3

If you are looking to transform any data into an array, give this custom method a try:

declare global {
  interface ArrayConstructor {
    create<T>(value: T | T[]): T[];
  }
}
export function MakeArray<T = any>(input: T | T[]): T[] {
  return Array.isArray(input) ? [...input as T[]] : [...[input as T]];
}
Array.create = function <T = any>(input: T | T[]): T[] {
  return MakeArray<T>(input);
}

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

"Upon querying with an AJAX POST request, the return value was

I'm encountering an issue where I am attempting to send data from JavaScript to PHP, make a database request, and have the result returned to my JS. However, all I get is "null" as a result. I have verified that my query is correct. Here is the JS cod ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

What is the best way to change an http call in a controller to a Service/factory pattern that accepts a parameter?

Currently, I have a controller making use of http.get, http.push and http.post methods within my AngularJS app. During my learning journey with AngularJS, I've discovered that it's more efficient to place http.get calls in service files. While I ...

What is the best method for importing a single module within a monorepo project using JavaScript and NPM?

I've organized my codebase into a monorepo with the following structure: ➜ yw git:(master) tree . ├── package.json ├── packages │ ├── common │ │ ├── package.json │ │ ├── src │ │ │ ├─ ...

Unable to locate JavaScript files within the Django project

I utilized Python 3.7 on Windows 10 to develop a Django project. settings.py: STATIC_URL = '/static/' LOGIN_URL = '/login' LOGIN_REDIRECT_URL = '/' https://i.sstatic.net/LSAdq.png I employed superuser to create some regu ...

What is the best way to obtain the date time format when making an Ajax request?

I am looking to create an Excel file named "myOrder" with a suffix of the current date. Is there a way to generate a filename in the format of "yyyyMMddhhmmss", for example, "20220704073533"? $.ajax({ url: kendo.format('@(Server.UrlDecode(U ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

The process of implementing sticky headers that stay in place while scrolling in a React application

I have a challenge with organizing tables based on date, using headers like (today, yesterday, last week, ...) and I want to make them sticky depending on the current table in the viewport. I attempted to implement this functionality using the react-sticky ...

Why is the Bootstrap tooltip flickering and not closing on mouseout? And why are duplicate entries not being triggered?

I'm facing some issues with the code I have here: Check it out The problems are as follows: Flickering - When hovering over the images slowly, there is noticeable flickering in the tooltip box rendering 2-3 times. This seems to be related to the cla ...

Accessing the FB Page plugin directly within the app browser

Utilizing the Facebook page plugin in a hybrid app created with worklight (6.2.01) looks like this: <div id="facebook-toc-feed" className="toc-feed"> <iframe id="fb-feed" src={"https://www.facebook.com/plugin ...

Launching a web application on Vercel, the back-end has yet to be initialized

I am currently working on a Next.js/TypeScript web application project hosted on Vercel's free tier. To run my project, I use npm run dev in the app folder to start the front end and then navigate to the back-end folder in another terminal and run npm ...

What is the correct way to send a GET request in angular?

Trying to make a GET request from Angular to Spring Java, but encountering error code 415 zone.js:3243 GET http://localhost:8080/user/friend/1 415 Below is my Spring Java code for the endpoint: @RequestMapping( value = "/friend/{idUser}", ...

instructions on transferring the data to the state without altering it

My data is stored in an array within a file named 'external-data.js' like this: `` export const mydata = [ { name: "john", age: 20, man: true }, { name: "julia", age: 22, man: false } ]; `` In ...

What is the best way to deactivate buttons within a button-group using Bootstrap?

I am dealing with a button-group that resembles the one shown in the image below: https://i.sstatic.net/U2AXN.png The code for this button-group is as follows: <span class="btn-group" data-toggle="buttons"> <span class="btn btn-default active ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

What is the best way to increase the value of a text box with jquery?

How can I increase the value of #hidtr using jQuery? <script type="text/javascript"> $('#hidtr').val(parseInt($('#hidtr').val()+1)); alert($('#hidtr').val()); </script> ...

The information I am trying to send to my node.js server is not getting returned to the client

As a newcomer to node.js, I wanted to sharpen my skills by working on a simple program. The goal was to assess the connection between the client and server using node.js, express, and socket.io. Let's take a look at server.js // Setting up an HTTP se ...

The swipe gesture triggers my React function to run twice, when not in strict mode

Having an issue with the swipe functionality on list items in my React application. The left swipe works correctly, but for some reason the right swipe function is triggered twice. Eliminated React StrictMode as a potential cause of the problem. Simplifie ...

Changing the selected value in a dropdown menu when the first dropdown is selected

Currently, I am facing an issue where changing the value of the first dropdown also changes the value of the second dropdown. How can I resolve this issue? I want to ensure that when I change the value of the first dropdown, the second dropdown does not i ...