Merge two functions that are alike into a single function

I am faced with a challenge of combining two similar functions that have some minor differences:

private filterByOperationType() {
    let operationBuffer: IProductOperation[] = [];
    if (this.filterConditions[0].selected.length > 0) {
      operationBuffer = this.operations.filter(({ operationDetails }) => {
          let operationType = false;
          for (const details of this.filterConditions) {
            if (details.name === 'Type') {
              const parsedGroup = details.selected[0].text;
              if (parsedGroup === operationDetails) {
                operationType = true;
              }
            }
          }
          return operationType;
        });
      }
    return operationBuffer;
  }

  /** Filter the operations by function group when dropdown is used */
  private filterByFunctionGroup() {
    const filteredData = this.operations.filter(({ functionDetails }) => {
      let groupDescriptionMatch = false;
      for (const details of this.filterConditions) {
        if (!details.selected[0]) {
          return;
        }
        if (details.name === 'Function group') {
          const parsedGroup = details.selected[0].text.match(/[a-zA-Z]+/g);
          if (parsedGroup?.join(' ') === functionDetails) {
            groupDescriptionMatch = true;
          }
        }
      }
      return groupDescriptionMatch;
    });
    return filteredData;
  }
}

Although both functions are filtering the same object, they target different keys (type and function group). The function group value undergoes a regex transformation since the dropdown value includes an index number and dash which is not accounted for in the logic. For example:

1 - myFunctionGroup --regex-->myFunctionGroup

This modification is not applied to the type key. How can these two functions be combined effectively?

Answer №1

It seems like the main struggle here is not just about separation of concerns, but also about reusability and abstraction. After some rewriting to improve readability, I realized that most of the work can be simplified using language constructs, leaving only the essential business logic.

Once you focus solely on the business logic, it becomes clear that no refactoring is necessary due to its simplicity.

const filterByOperationType = () => {
  if (!filterConditions[0].selected.length) {
    return [];
  }

  return operations.filter(({ operationDetails }) => {
    return filterConditions.some(fc =>
      fc.name === "Type" && fc.selected[0].text === operationDetails,
    );
  });
};

/** Filter the operations by function group when dropdown is used */
const filterByFunctionGroup = () => {
  if (!filterConditions[0].selected.length) {
    return [];
  }

  return operations.filter(({ functionDetails }) => {
    return filterConditions.some(fc =>
      fc.name === "Function group"
      && intoLetterOnlyWords(fc.selected[0].text) === functionDetails,
    );
  });
};

// Perform custom transformation on text
const intoLetterOnlyWords = (text) => text.match(/[a-zA-Z]+/g).join(" ");

If you want to enhance this further, consider creating a higher-order function to encapsulate the concerns of each filtering function.


const createFilterBy = (nameToMatch: string, formatSelectedText = (t: string) => t) => () => {
  if (!filterConditions[0].selected.length) {
    return [];
  }

  return operations.filter(({ functionDetails }) => {
    return filterConditions.some(fc =>
      fc.name === nameToMatch
      && formatSelectedText(fc.selected[0].text) === functionDetails,
    );
  });
};

// Perform custom transformation on text
const intoLetterOnlyWords = (text: string) => text.match(/[a-zA-Z]+/g).join(" ");

const filterByFunctionGroup = createFilterBy("Function group", intoLetterOnlyWords);
const filterByOperationType = createFilterBy("Type");

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 path('/') in $rootScope is not functioning properly

Below is a function called register() that I am working with. <form class="form-auth" ng-submit="register()"> This is how I have defined the register function: $scope.register = function(){ $http.post('/auth/signup', $scope.user).success ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

When attempting to upgrade from Angular 10 to 13, users may encounter the following error message: "TS2307: Unable to locate module 'path_to_service' or its corresponding type declarations."

I initially developed my Angular App using the paper-dashboard template with Angular version 10.0. Recently, I upgraded to Angular version 13 and switched to a different template - WrapPixel. However, I encountered an error when trying to include a servi ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

When Vue.js is compiled, it removes a script tag

I'm currently learning Vue.js and encountering an issue that I can't seem to resolve. My project is utilizing Vue CLI 3, and within my code I am inserting a custom tag (not a component) in my template with a script tag inside it. <ra type="ou ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

Is it possible to dynamically append and delete rows of interconnected dropdown menus?

I'm currently working on a form that allows users to add and remove rows with cascading dropdowns for class selection. Everything is functional except for the feature to remove selected classes. I've experimented with different methods like the ...

Using Node.js to parse JSON data fetched from the web

My current challenge involves retrieving and parsing JSON from a web API (https://api.coinmarketcap.com/v1/ticker/?limit=3) in order to extract the name and price_usd fields. For example: [ { ... sample data provided ... } ] The code snippet I am wo ...

Is it possible to develop in React without using webpack, relying solely on Gulp instead?

Although I appreciate some aspects of Webpack, my enthusiasm for it wanes as the configuration files grow beyond 15 lines. It becomes overly cryptic, difficult to configure, and time-consuming. Therefore, I tend to reserve its use for just a couple of task ...

Encountering repeated requests (duplicating calls) for each API request while using AngularJS with a JWT authentication token

I'm experiencing a problem with AngularJS(2/4) while attempting to make API calls. The issue arises when each API request contains a JWT Auth Token header, resulting in duplicate API calls. The first request returns no response (despite receiving a 20 ...

Maintain your position on the current page when refreshing Angular 4

My Anuglar 4 application features multiple routes, with two main ones being Logging and List of items. Specifically, the routes are http://localhost:4200/#/ and http://localhost:4200/#/items. However, I've noticed that when I reload the page while on ...

What is the most effective way to utilize getStaticPaths in a dynamic manner within next.js

There is a need to paginate static pages for each of the 3 blog categories, but the problem lies in the variable number of pages and the inability to access which category needs to be fetched in getStaticPaths. The project folder structure appears as foll ...

Developing HTML components for the purpose of testing JavaScript

I am encountering a specific issue in my react component where I am using the following commands: document.getElementById('modalsContainer').appendChild(recognitionProfileZoom); document.getElementById('modalsContainer').appendChild(ca ...

Navigating with buttons in React JS

In my material-ui, I have a button set up like this: <Button style={green} raised="true" label="Continue to create group"}> CREATE NEW GROUP </Button> I am looking to make it so that when the button is clicked, it will take me ...

Angular 2: Copious Errors in the Mix

Working on building an Ionic 2 app using the Angular 2 framework, I encountered a problem when trying to display a map on a page. I found a helpful guide at the following link: While the map was working fine, I started getting an error in my console: You ...

Is there a way to cancel a fetch request and initiate a new one right away?

Below is an illustration taken from MDN. The example showcases two buttons - one for sending a request and the other for canceling it. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector(&apos ...

Guide to naming Vite build JS and CSS bundles in Vue

As I work on building a SPA using Vite+Vue3 and JavaScript, I have encountered an issue when running npm run build. After making changes, the resulting .css and .js files have names that appear to be generated from a hash, which is not ideal. I would like ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...