Is there a way to optimize two methods that share similar logic but differ only in the operators they utilize?

  validateToken(type: TOKEN_TYPES, symbol: string, shouldMatch: boolean) {
    let isTrue = false;
    
    if (shouldMatch) {
      if (
        this.tokenizer.getCurrentToken() === symbol &&
        this.tokenizer.tokenType() === type
      ) {
        isTrue = true;
      }
    } else {
      if (
        this.tokenizer.tokenType() !== type ||
        this.tokenizer.getCurrentToken() !== symbol
      ) {
        isTrue = true;
      }
    }

    return isTrue;
  }

By combining the functionality of the assertToken and assertNotToken methods into a single function called validateToken, we have achieved code consolidation and reusability.

Answer №1

If you want to make a modification, you can update the second one like this:

assertNotToken(type: TOKEN_TYPES, symbol: string) {
    return !assertToken(type, string);
}

Alternatively, if you prefer not to have two separate functions, you can simply remove the assertNotToken function entirely and just negate assertToken(type, string) whenever needed.

Answer №2

The comparison inside the initial function's `if` statement is essentially the inverse of that found in the second function (De Morgan's laws). To address this, consider introducing a third parameter to specify the type of assertion, allowing for the return of either `isTrue` or `!isTrue`.

checkTokenValidity(type: TOKEN_TYPES, symbol: string, isAssertion: boolean) {
  let isTrue = this.tokenizer.getCurrentToken() === symbol 
                && this.tokenizer.tokenType() === type;

  return isAssertion ? isTrue : !isTrue;
}

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

Angular 2 Beta Faces Issues with Loading Dynamic Routes

I am currently working on dynamically loading routes for the @RouteConfig from a service that fetches data in JSON format. [ { "path" : "/about" , "name" : "About" , "component" : "AboutComponent" }, { "path" : "/contact" , "name" : "Contact" , "compo ...

Validate if the Jquery AJAX response contains any data

I've been attempting to integrate an alert message in my code that triggers if the response is null, but every time I try to do so, something goes wrong. If anyone has any suggestions or assistance with this issue, it would be greatly appreciated. He ...

What is the best way to call a JavaScript function that is embedded within a string?

I have a variable named 'content' that contains HTML code. When a user clicks on a button, the innerHTML of a div is set to the value of content. However, I want it to execute any function included in the string. For example: Function: functi ...

Create static HTML files using an Express server

Recently, I developed a nodejs web project using express-js and ejs. However, upon further reflection, it occurred to me that hosting it as static html files on Netlify might be more cost-effective than running it as a nodejs app on Heroku. Since the data ...

Modifying the data of an HTML form using Javascript, encrypting the information, and transferring it to PHP

I am new to PHP and have a simple code management question. I would like to create an input box in HTML where someone can enter their name, and with the use of Javascript, generate a link with an encoded version of the name preceded by a website string. Wh ...

Adjust the size of an element using the jQuery library's knob.js

There is a page Once the button is pressed, a circle element from the library jquery.knob.js appears. I am trying to change the size of the circle and have written this code: <div style="float:left; width:255px; height:155px"> <input ...

Using AJAX to manipulate the document structure and execute a function

Currently, I am operating on Linux -both browser side & server side- using either Firefox 38 or 42. For more context, you can refer to this question and the GitHub project containing my GPLv3 code. The web application is not standard as it typically has on ...

Utilizing Angular's ng-model directive in combination with the required

I am attempting to implement a basic input field using html5 "required". The input field utilizes placeholder text, so I want the initial value of the input to be blank. I have connected the input to an ng-model that is set as empty initially to display th ...

Encountering an 'undefined' result while attempting to retrieve context from provider in TypeScript/React

As a novice in TypeScript and React Hooks, I am endeavoring to learn by building a simple todo app. Your patience is appreciated during this learning process: I have been attempting to establish a global state using the useContext and useState hooks. Alth ...

Is there a way to automatically hide a div based on a checkbox value when the page loads?

How can I hide a div in my view when a checkbox is not checked upon page load? <input type="checkbox" class="k-checkbox" id="chkInvoiceStatusActive" asp-for="InvoiceStatus" value="true" /> <input t ...

What is the process for acquiring a comprehensive catalog of Node.js modules?

Currently, I am working on integrating NPM functionality into my Node.js applications. My goal is to be able to analyze the node modules available on my system. When referring to a "module" in this context, it could either be an identifier like "fd" or a f ...

The error message "ReferenceError: obj is not defined using webcomponents & polymer" indicates that the object

I am diving into the world of web components for the first time with this project, and my knowledge of js/jquery is quite limited. I'm encountering an issue and I'm unsure why it's happening. I've created a custom element in "search-fo ...

Setting default zoom level for Google Map in HTML

Initially, the map for the second city is hidden. When the second button is clicked, the map for the first city will be hidden and the map for the second city will be displayed. However, in this case, the map for the second city appears zoomed out. How can ...

Tips for resolving the error "React import attempt":

I'm a beginner in learning React and I encountered this error when trying to export NavigationMenu and import it into Navigation: Failed to compile ./src/components/Navigation.js Attempted import error: 'NavigationMenu' is not exported from ...

The method for retrieving and entering a user's phone number into a text field upon their visit

Objective: To enhance the user experience by automatically filling in the phone number input field when a mobile user views the page, making it easier to convert them into leads. A privacy policy will, of course, be in place. This page will offer a promo ...

Troubining AJAX for Generating a New Template: Addressing Missing Template Error

I have been working on integrating AJAX into my to-do application, but I keep encountering a missing template error (Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :bu ...

Implementing custom click event for selecting checkboxes in Material-UI table rows

I have been working with the material-ui data table to implement sorting functionality. One feature I am trying to add is a checkbox on each row. The challenge I am facing is that when clicking on the checkbox, it also triggers the row link, which is not t ...

Tips for ensuring the "keep-alive" functionality of a component stays active when using router-view in Vue 3

I have successfully developed a small application with two main components using vue router for navigation. The first component is named MoviesList and the second one is Movie. I have defined them in the routes.js file. const routes = [ { path: &apo ...

How to extract keys from an object using jQuery

I am currently working on implementing a Modal in bootstrap 5. I found a helpful guide at http://jsfiddle.net/341tfz8j/1/. I made the necessary changes to update the references from bootstrap 4 to bootstrap 5, such as changing data-toggle to data-bs-toggle ...

Error: Property '' is not found in type 'Object'. Observable subscribe

Recently delving into Angular2, I encountered a perplexing issue. I created some mock data like so: export const WORKFLOW_DATA: Object = { "testDataArray" : [ { key: "1", name: "Don Meow", source: "cat1.png" }, { key: " ...