Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this:

    this.something = function (which) {
        // Can be one or many.
        if (!Array.isArray(which)) {
            // Single input case.
            doSomething(which);
        } else {
            // Multiple inputs case.
            which.forEach(function (thing) {
                // Utilizing recursion
                something(thing);
            });
        }
    };

Any suggestions for a more concise approach?

Answer №1

this.action = function(selected) {
    (Array.isArray(selected) ? selected : [selected]).forEach(function(element) {
        performAction(element);
    });
};

Answer №2

Although it's not something I typically prefer, it's a common approach in coding:

// A function that processes values either as a single parameter or within an array
var doSomething(x) {
  if (Array.isArray(x)) {
    x.forEach(doSomething);
  } else {
    console.log(x);
  }
}

You can separate this logic from doSomething and encapsulate it in a utility method like this:

var ifArrayForEach = f => x => Array.isArray(x) ? x.forEach(f) : f(x);

var doSomething = x => console.log(x);

var doSomethingArrayOrNot = ifArrayForEach(doSomething);

doSomethingArrayOrNot("Hello world");
doSomethingArrayOrNot(["Hello", "world"]);

Once again, it may not be my preferred approach, but there are times when it can prove useful. Personally, I would opt to check before calling the function. Ultimately, you need to understand the data you're working with at some point anyway...

Answer №3

Uncertain if this aligns with what you're seeking in terms of tidiness, but one approach could be to use a try/catch block.

try {
  which.forEach(function (thing) {
    something(thing);
  });
} catch (e) {
  if (e instanceof TypeError) {
    doSomething(which);
  }
}

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

Load elements beforehand without displaying them using a div

In order to efficiently manipulate my Elements using jQuery and other methods, I am exploring the idea of preloading them all first. One approach I have considered is creating a div with CSS display set to none, and placing all the elements I need for my w ...

The React DOM element undergoes mounting and unmounting on each render cycle when it should be simply altered/updated

As per the React documentation, callback refs are invoked during both component mounting (with the DOM element's value) and unmounting (with null): When a React component mounts, the ref callback is triggered with the actual DOM element, and when it ...

The Ajax URL is failing to connect with the controller through IIS

I am facing an issue where the application gets stuck in the Home controller when running it on IIS. It doesn't progress to the next controller (Data controller) as specified in the URL. However, when I run it in debug mode, everything works fine. How ...

The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files? file1.js file2.js The code inside file1.js is as follows: var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json([&apo ...

What led to the decision for the two distinct chart elements to merge into a single container?

In the process of creating a dashboard using React.js and d3.js, I encountered an interesting issue that perplexed me for quite some time. Below is the Scatterplot.js code written in d3.js: import React, { Component } from "react" import * as d3 from "d3 ...

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

Alter a prototype method belonging to another module

If I wanted to create a custom plugin or module that alters the behavior of an object exported in another module, how can I go about modifying one of its methods? The code below illustrates my attempt at achieving this, but it seems like there may be a cru ...

Error Encountered: Invalid Parameter Type when Retrieving Item from AWS Dynamo

I've been facing issues when trying to establish a connection between my ReactJS application and AWS DynamoDB. Despite confirming the correctness of the API key, secret key, and region, I keep encountering an InvalidParameterType error. I have even at ...

Sending a variable from JavaScript to an external PHP file

There are numerous questions on similar topics, but I'm struggling to figure it out, my apologies. I have a file containing some JavaScript variables that depend on user input (without using a form) and a normal HTML link to my PHP file. <script& ...

Interop-require-default is nowhere to be found in the babel-runtime

I'm really stuck on how to resolve this error. I've tried searching online and followed the suggestions given by others. I even went as far as deleting 'node_modules' and reinstalling, but nothing seems to be working. The specific erro ...

PHP problem with submitting an array of checkboxes

Having an issue with checkbox array This is the code snippet <?php include('config.php'); if(isset($_POST['submit'])) { for($x = 0;$x <= 5;$x++) { if(isset($_POST['check'][$x])) { ...

Issue with large date changes causing MUI DatePicker to freeze

The MUI DatePicker, whether from Labs or X, was functioning perfectly. However, I am now facing an issue where it hangs when trying to change the date by ten years. It appears that the code gets stuck in an endless loop, yet there are no errors displayed i ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

What is the best way to showcase an element within an array that matches a particular value or character?

I have obtained a JSON array from hxxp://best1st.info/Moviedb/json.php?m=tt2015381&o=json Here is a snippet of the array output: . and so on . . [STORYLINE] => On planet Earth in 1988, young Peter Quill ( ) sits in the waiting room of a hospital. ...

The function does not have the capability to yield elements within the returnSize array as requested in the problem statement

Recently, I tackled a C coding problem known as Two Sum on the online platform LeetCode. Despite my efforts, I'm struggling to properly return the integer pointer size. Here is the question: Given an array of integers, find the indices of two number ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Every single data attribute is unique for each element

Hello! I'm currently working on creating a sorting system for pictures, documents, and videos. Each div contains data-extension attributes, so my plan is to filter out all attributes that are jpg, gif, or png and make them visible while hiding the oth ...

Is there a way to update a data element within a $.get request by utilizing information from a JSON array?

Is there a way to dynamically change a data element in a $.get request using values from a JSON array? Let's take a look at an example code snippet that achieves this: $.get(url, { 'p': testerName, ...