This function has a Cyclomatic Complexity of 11, exceeding the authorized limit of 10

if ((['ALL', ''].includes(this.accountnumber.value) ? true : ele.accountnumber === this.accountnumber.value) &&
        (['ALL', ''].includes(this.description.value) ? true : ele.description === this.description.value) &&
        (['ALL', ''].includes(this.country.value) ? true : ele.country === this.country.value) &&
        (!this.entryDate ? true : (this.entryDate === dateEntry)) && 
        (!this.editedDate ? true : (this.editedDate === dateEdited))) {
        return true;
      }

Answer №1

It can be beneficial to write additional code to gain a deeper understanding of the process.

An initial suggestion is to elaborate on the content within your if statement like this:

Keep in mind that using a simple || operator instead of ternary is also effective.

PS: I have used poor variable naming without considering the purpose behind your actions. When reusing the following code, ensure to change them and provide comments explaining your intentions.

const isA = [
 'ALL',
 '',
].includes(this.accountnumber.value) || ele.accountnumber === this.accountnumber.value;

const isB = [
  'ALL',
  '',
].includes(this.description.value) || ele.description === this.description.value;

const isC = [
  'ALL',
  '',
 ].includes(this.country.value) || ele.country === this.country.value;

const isD = !this.entryDate || this.entryDate === dateEntry;

const isE = !this.editedDate || this.editedDate === dateEdited;

if (isA && isB && isC && isD && isE) {
  return true;
}

Expanding upon this will highlight duplicated sections of code.

function checkCond(key, obj, arr = [
  'ALL',
  '',
]) {
  return arr.includes(this[key].value) || obj[key] === this[key].value; 
}

const isA = checkCond('accountnumber', ele);
const isB = checkCond('description', ele);
const isB = checkCond('country', ele);

const isD = !this.entryDate || this.entryDate === dateEntry;

const isE = !this.editedDate || this.editedDate === dateEdited;

if (isA && isB && isC && isD && isE) {
  return true;
}

Taking it one step further:

function checkCond(key, obj, arr = [
  'ALL',
  '',
]) {
  return arr.includes(this[key].value) || obj[key] === this[key].value; 
}

const conditions = [
  checkCond('accountnumber', ele),
  checkCond('description', ele),
  checkCond('country', ele),

  !this.entryDate || this.entryDate === dateEntry,
  !this.editedDate || this.editedDate === dateEdited,
];

if (conditions.every(x => x)) {
  return true;
}

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

Creating and handling Observable of Observables in RxJS: Best practices

Within my Angular application, there are multiple services that have dependencies on each other. To manage this, I have created a dependency map as shown in the example below: let accountInitialization$: Observable<void>; let productInitialization$: ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

What is the best way to efficiently filter this list of Outcome data generated by neverthrow?

I am working with an array of Results coming from the neverthrow library. My goal is to check if there are any errors in the array and if so, terminate my function. However, the challenge arises when there are no errors present, as I then want to destructu ...

What are some techniques for streamlining this code with Typescript?

I am currently working with the following code snippet: let doNavigate = this.currentScreen === removedFqn; if (doNavigate) { location.reload(); } Does anyone have any suggestions on how I can simplify this code using Typescript? ...

Error: The token 'export' in d3zoom is causing a syntax issue

I'm encountering issues with executing tests in Angular: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export {default as zoom} from "./zoom.js"; ...

Angular 2 Issue: @Input() Directive Not Recognized - Unresolved Reference Error

I am a beginner trying to grasp Angular2 concepts from ng-book 2(v49). Below is the code snippet from article.componenets.ts file: import { Component, OnInit } from '@angular/core'; import { Article } from './article.model'; @Componen ...

Display a complete inventory of installed typings using the tsd command

How can I display a list of all installed tsd typings in the terminal? Perhaps using the following command: $ tsd list ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

Cypress has the ability to exclude certain elements from its testing

How do I locate a clickable element using the cypress tool? The clickable element always contains the text "Login" and is nested inside the container div. The challenge lies in not knowing whether it's an <button>, <a>, or <input type=& ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...

Incorporating a module with the '@' symbol in a Node, Express, and Typescript environment

I recently started using Node and Typescript together. I came across a file where another module is imported like this import { IS_PRODUCTION } from '@/config/config';. I'm confused about how the import works with the @ symbol. I could real ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

Discovering a specific string within an array of nested objects

Seeking guidance on creating a dynamic menu of teams using JavaScript/TypeScript and unsure about the approach to take. Here is an example dataset: const data = [ { 'name': 'Alex A', 'agentId': '1225& ...

Ways to assign unpredictable values (such as ids, dates, or random numbers) to a Domain Entity or Aggregate Root when it has been injected as dependencies

I am currently developing a frontend repository that follows an innovative hexagonal architecture approach with domain-driven design principles, and it utilizes Redux Toolkit. The development process involves Test-Driven Development (TDD) where I employ c ...

What distinguishes between a public variable declared as var: any = []; versus a public variable declared as var: any[] =

I'm seeking clarification on the distinction between the following: public var: any = []; // versus public var: any[] = []; ...

How can I set the default bindLabel for a dropdown in @ng-select/ng-select when the self change event occurs in Angular

I have a scenario where I need to set the default value to null in the ng-select. If the user selects an option from the dropdown first, then on the change event it should check if the Amount model is not null or blank. If the Amount model is blank, then ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Error: Unable to cast value to an array due to validation failure

I'm currently working on integrating Typegoose with GrqphQL, MongoDB, and Nest.js for a project. My goal is to create a mutation that will allow users to create a post. I have set up the model, service, and resolver for a simple Post. However, when I ...

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...