What is the best way to merge these functions?

As I dive into JavaScript functions, I find myself with three almost identical ones:

function filterAll() {
    location.hash = "/"
}

function filterCompleted() {
    location.hash = "/completed"
}

function filterActive() {
    location.hash = "/active"
}

I wonder if there's a way to consolidate these functions into one, where I can specify the desired parameter each time I call it. Here's my attempt at restructuring them:

function filters(filterType) {
    if (filterType === 'all') {
        location.hash = "/";
    } else if (filterType === 'completed') {
        location.hash = "/completed";
    } else if (filterType === 'active') {
        location.hash = "/active";
    }
}

filters('all');

Answer №1

To easily map different actions to URLs, you can utilize an object literal in JavaScript like this:

const actions = {
  all: '/',
  completed: '/completed',
  active: '/active'
}

function filter(action) {
  location.hash = actions[action];
}

// Usage example
filter('all');
filter('completed');
filter('active');

If passing a string is not desired, another approach would be treating the object as an enumeration:

function filter(action) {
  location.hash = action;
}

// Usage example
filter(actions.all);
filter(actions.completed);
filter(actions.active);

While using multiple consts can work as mentioned by others, I prefer to keep things simple and avoid excessive variable declarations.

Answer №2

I'm not entirely certain about your intentions, could you please provide some additional context? If your goal is to pass three variables, then the code snippet you shared appears to be suitable. However, if you are looking to pass a single variable with three data points, I would recommend utilizing an object.

var selections = {first:"/", second: "/completed", third: "active"};

You can access the values by using a method like alert(selections.first);

Answer №3

Here is a possible solution for you to consider:

function filterItems(value) {
    switch (value) {
        case 'all':
            location.hash = "/";
            break;
        case 'completed':
            location.hash = "/completed";
            break;
        case 'active':
            location.hash = "/active";
            break;
        default:
            break;
    }
}

Answer №4

If you want to streamline your code, consider combining the three functions below into a single function that only requires one parameter.

Step One

To start, define three const variables:

const all = '/';
const completed = '/completed';
const active = '/active';

Step Two

Next, create the following function:

function myFilter(filterType) {

  location.hash = filterType;
}

Step Three

Now you can call the function with different values:

  • myFilter(all);
  • myFilter(completed);
  • myFilter(active);

Answer №5

It seems like this is the solution you've been searching for.

function sortOptions(optionType) {
    if (optionType == 'ascending') location.hash = "/asc";
    if (optionType == 'descending') location.hash = "/desc";
}

While I suggest a different approach, here is an example of how to use the function:

sortOptions('ascending'); // Set ascending order
sortOptions('descending'); // Set descending order

Answer №6

Initially, it is important to establish these variables as constants, solely for the purpose of serving as parameters for actions.

The following code snippet can be utilized:

function filters ( action ) {
 return action==="all" ? location.hash = "/" : action==="completed" ? location.hash = "/completed": action==="active" ? location.hash = "/active" : "No Match Found";
}

In order to evaluate the function, a straightforward example has been provided:

let tod = "all"; 
let com = "completed"; 
let act = "active";

//Upon executing this code in your browser, you will have access to all necessary information.

[filters(tod),filters(com),filters(act)].forEach;

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

The toggle feature in Bootstrap is stuck in the "on" position and refuses to "untoggle."

Currently, I am working on developing a basic website using Laravel and Vue.js. To ensure that the website is responsive, I integrated Bootstrap 4 into the project. For the most part, everything appears to be functioning correctly - the navbar collapses as ...

Vue.js v-else-if directive not functioning properly: Unable to resolve directive: else-if

I am encountering a compilation error while using "if" and "else-if". [Vue warn]: Failed to resolve directive: else-if Here is the code I am working with: var app = new Vue({ el:"#app", data:{ lab_status : 2 } }); <script src="https: ...

Is there a way to eliminate the pop-up window background in MUI?

Is there a way to get rid of the white pop-up background in MUI's default CSS? <Dialog open={open} onClose={() => { setOpen(false); }} > <DialogContent> <h1>Do you really ...

Framer Motion's "repeatType" property triggering a TypeError

Every time I try to add the repeatType property in my transition, I encounter an error related to the variants prop: index.d.ts(2779, 5): The expected type comes from property 'variants' which is declared here on type 'IntrinsicAttributes ...

When resizing the window, the width change in JQuery always resets to 0

I've been trying to adjust the width of a div element when the window is resized, but for some reason, the width always ends up being 0 after the resize event. function resizeUploadField() { var uploadInputField = $('.input-append&apo ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

``The Vue.js routing system is determined by the incoming data received

Working with VueRouter to navigate to a component based on payload. { path: '/foobar', name: 'foobar', component: foobar, } { path: '/foobar', name: 'foobarSuccess', component: foobarSuccess, query: { ...

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

Guide to showing specific images alongside text through Ajax and Jquery

Currently, I am faced with the challenge of displaying specific text files using jQuery and Ajax. My goal is to have a text file appear based on the image being displayed. For instance, if an image of an apple is being shown, I would like the text below i ...

Obtain the response body in Nest JS middleware

Currently, I am working on developing logging middleware for my project. My main goal is to log the response body specifically in 500 responses. However, I have encountered an issue where the response body is not present in the Response object when using a ...

How can we effectively utilize LESS variables in styles.less when working with LESS files within components in Angular versions 6 or 7?

Running Angular version 7.0.0 will generate a folder structure typical for "ng new". Below is the content of my styles.less file: @personal-black: #0000; This snippet shows the content of my app.component.less file: ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

"Learn the steps to create a Python function that calculates the count and percentage of zero values in each column of a dataset, then exports this information to an

I am dealing with a dataset that has 780 columns and 87529 rows, many of which contain zero values. The code I am currently using is giving me a result in the format of 780*2 lines, making it hard to read and comprehend. I am looking to export this resul ...

Unexpected behavior of jQuery in Internet Explorer

I'm grappling with a challenge and need some assistance. Despite my efforts, I can't pinpoint the exact source of the issue... The problem lies within an interactive graphic designed for Chrome users. This graphic includes variables that change ...

Constantly scrolling screen in android Webview

When working with an Android web view, I encountered a bug related to infinite scrolling. Interestingly, removing the routerLink in certain pages resolved the issue, but not consistently across all cases. Is there a way to address this bug from the Android ...

Is there a way to change the entire background color of my popover?

Hi there! My issue is that the arrow in my popover isn't changing color and is still showing up as white. Here is the current code: http://jsfiddle.net/GZSH6/19/ Here is the CSS code: .popover { background: #BE7979; color: white; borde ...

Vue/Vite vanilla setup encountering a 'Failed to fetch dynamically imported module' TypeError

We're currently working with a vanilla Vue/Vite setup and I'm encountering the error message TypeError: Failed to fetch dynamically imported module in Sentry logs. It appears that these errors coincide with new deployments to production, but I d ...

Having difficulty accessing attributes within the template - encountering errors for all attributes except for 'name', stating '[attributename] is not defined'

There seems to be an issue with accessing Object attributes other than 'name' in the template. When trying to access attributes like id or url, errors such as 'id/url/whatever is not defined' are logged in the console. The JSON file pas ...

Troubleshooting Mongoose and MongoDb Connectivity Issues

Previously, I had no trouble connecting to Atlas from my home wifi, but I encountered issues at Starbucks. After switching to google fiber, I am now facing this error. at Pool.<anonymous> (/Users/j/Desktop/projects/templateApp/node_modules/mong ...

Error encountered: The function 'showErrorMessage' is not exported from the file '../helpers/alerts'

Within the directory ../helpers/alerts, there is a file called alerts.js const displaySuccessMessage = (success) => { <div className="alert alert-success">{success}</div> } const displayErrorMessage = (error) => { <di ...