What is the best way to create a TypeScript function that merges actions together?

I am currently working on a TypeScript function similar to the following:

    import multipleActionObject from page; 
    it("should be able to perform multiple operations", () => {
        multipleActionObject.chooseIndex(4).setValue(10);
    }

Instead of writing it like this:

   import multipleActionObject from page; 
    it("should be able to do multiple operations", () => {
        multipleActionObject.chooseAndSetNumber(4,10);
    }

Within my multipleActionObject class:

class multipleActionObject(){

        public chooseAndSetNumber(index,value){
           this.index[index].setValue(value)
        } 
 }

Is there a way I can create a helper function for the first approach?

Answer №1

To make use of the chooseIndex method in assigning an index property to the instance, followed by the retrieval of that index using the setValue method, you can implement a simple logic as shown below:

class actionModifierObject {
  constructor(array) {
    this.array = array;
  }
  
  chooseIndex(indx) {
    this._index = indx;
  return this;
}
  
setValue(val) {
   if (typeof this._index !== 'number') {
      throw new Error('No index assigned to set value');
    }
this.array[this._index] = val;
return this;
}

const obj = new actionModifierObject([5, 6, 7, 8]);
obj.chooseIndex(2).setValue(15);
console.log(obj.array[2]);

The concept demonstrated above is known as "method chaining", although it may seem unconventional to separate the selection process from the subsequent operation performed on that object.

Answer №2

Learn about the benefits of using a fluent interface

class multipleActionClass
{    
  selectIndex(index) {
      this.currentIndex=index;   
      return this;
  } 

  enterValue(value) {
      console.log(`set value ${value} at index ${this.currentIndex}`);
      // this.index[this.currentIndex].setValue(value) ...
      return this;
  } 
}

let multipleActionObject = new multipleActionClass();

multipleActionObject.selectIndex(1).enterValue(2);

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

Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request. By enabling logging in TypeORM, I am able to observe the e ...

transferring data from service to component

Dealing with the challenge of passing a variable from a service (LibraryService) to a component located one level deeper in the directory structure (ReadingPaneComponent) has been quite troublesome for me. This predicament arose after successfully transfer ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

What is causing the failure of the state to be inherited by the child component in this scenario (TypeScript/React/SPFX)?

For this scenario, I have a Parent class component called Dibf and a Child class component named Header. While I can successfully pass props from the Parent to the child, I am encountering difficulties when trying to pass state down by implementing the fo ...

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

A guide on incorporating a set of components to be utilized as custom HTML elements in Angular

I am in the process of revamping my application to be more modular on the UI side, with a focus on separating different elements including: App header Left navigation panel Main content on the right side of the nav panel I have successfully figured out ...

Encountered an error stating "Cannot find module node:fs" while using eslint-typescript-import, eslint-import-resolver-typescript,

Challenge My attempt to configure path alias in my TypeScript project was met with failure. Two errors arose during the execution of npm start: Module not found: Error: Can't resolve '~/App' in 'D:\work\workbench\templa ...

Creating click event handler functions using TypeScript

I encountered an issue when trying to set up an event listener for clicks. The error message I received was that classList does not exist on type EventTarget. class UIModal extends React.Component<Props> { handleClick = (e: Event) => { ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

Guide to incorporating third-party libraries in Angular

Greetings, I have a common question regarding Angular and utilizing third-party libraries. As someone who does not frequently work with Typescript/Frontends, I am encountering an issue with Angular. Specifically, I am attempting to incorporate the node-htm ...

Develop customizable enumerations for use in expandable interfaces

Situation: My objective is to devise a strategy for building scalable state machines in TypeScript using the TypeState library. TypeState offers a typesafe state machine for Typescript, which while not directly related to my current issue, serves as a good ...

core.js:15723 ERROR TypeError: Unable to access the 'OBJECT' property because it is undefined

Whenever I attempt to run this function, I encounter an issue. My goal is to retrieve the latitude and longitude of an address from Google's API. This error message pops up: core.js:15723 ERROR TypeError: Cannot read property 'geometry' of ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

Passing information from the main component to a service through API connections

Currently, I am in the process of developing a website dedicated to showcasing the top 20 highest-rated Sci-fi movies. The main component on the homepage leverages a GET request via a service to fetch an array of objects containing the movie data. This mov ...

Cross-origin resource sharing (CORS) seems to be creating a barrier for the communication between my Angular

During the process of developing an Angular and NestJS app with NGXS for state management, I encountered a CORS error while serving my application. The error message in the console indicated: Access to XMLHttpRequest at 'localhost:333/api/product-i ...

A method to eliminate the mouse-over effect following the selection of an input box

Currently, I am utilizing Angular and encountering three specific requirements. Initially, there is an input box where I aim to display a placeholder upon pageload as 'TEXT1'. This placeholder should then toggle on mouse hover to display 'TE ...

Tips for sorting an array with various data types in TypeScript while explicitly defining the type

I need help with a class that contains two fields, each being an array of different types but sharing the common field id. I am trying to create a method that filters the array and removes an item based on the provided id. enum ItemType { VEGETABLES = &a ...

"Activate the mat-checkbox based on the outcome of a certain process

I'm working with a mat-checkbox that triggers a mat-dialog when clicked. If the user clicks "confirm" in the dialog, I want the checkbox to be checked. If they click "cancel", I want it to remain unchecked. How can I achieve this? Below is the method ...