Typescript's array of functions

In my code, I currently have an

engage(ability: number, opponent: Creature)
function that is responsible for executing one of three different attacks based on the ability chosen.

strike(opponent: Creature){}
claw(opponent: Creature){}
fireball(opponent: Creature){}

The issue I am facing is that the consequences of each attack method (such as the opponent dying) are repeated in my current implementation.

if(ability == 1){
   claw(opponent);
   *
   *
   lines detailing claw effects
   *
   * 
   *
}

else if(ability == 2){
   *
   *
   *
}
else {
  *
  *
  *
}

I am curious about the possibility of creating an array called attack_methods[3] which would simplify the process to define and execute attacks like this:

attack_methods[1] = strike(opponent: Creature){};
attack_methods[2] = claw(opponent: Creature){};
attack_methods[3] = fireball(opponent: Creature){};

and then call them using the following format:

engage(ability: number, opponent: Creature, attack_methods[]: DivineKnowledge){

     attack_methods[ability](Creature);
     *
     *
     *
     implications of the chosen ability
     *
     *  
     *

}

I am interested in understanding the correct way to implement this feature as I transition from programming in C to learning about TypeScript.

Answer №1

To achieve different implementations in a clean manner, consider using a map of choices and corresponding functions.

For better readability, the type of choice will be changed from number to string.

List all the choices as follows:

const CHOICE_TACKLE: string = "TACKLE";
const CHOICE_BITE: string = "BITE";
const CHOICE_LASER: string = "LASER";

Define the functions accordingly:

const tackle = (enemy: Monstor) => { 
    /** Tackle implementation */
}

const bite = (enemy: Monstor) => { 
    /** Bite implementation */
}

const laser = (enemy: Monstor) => { 
    /** Laser implementation */
}

You can organize these functions in separate files and then import them into a single file.

Once all choices and implementations are set up, create a map like this:

const ATTACK_IMPLEMENTATIONS = {
    [CHOICE_TACKLE]: tackle,
    [CHOICE_BITE]: bite,
    [CHOICE_LASER]: laser
}

Your attack function can now be written as:

const attack = (choice: string, enemy: IMonster) => { 
    const attackFunction = ATTACK_IMPLEMENTATIONS[choice];

    if (!attackFunction) { 
        console.error(`No attack function implementation found for choice "${choice}"`);
        return;
    } 

    attackFunction(enemy);
}

Keep in mind that this method simplifies code organization. For more complex scenarios, you may want to explore the strategy pattern.

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

Can you modify a attribute value in one HTML file from another?

I currently have a website and I am looking to modify the aria-expanded value of an expandable paragraph on another page when I click on an anchor element in the main page. What changes do I need to make in my main.html file in order to update the aria-exp ...

What is the best way to set up a list of states in React using hooks?

Suppose I have a variable, n, which can take on any value. My objective is to generate n input fields while maintaining the state of each input. However, I am currently facing challenges in figuring out how to achieve this. For instance, when n = 3, my des ...

Steps to successfully retrieve an image using JavaScript on the client side while circumventing any CORS errors

I have a React application where I am displaying an image (an SVG) and I want the user to be able to download it by clicking on a button. The image is stored in Firebase Storage. However, I am encountering an issue with CORS error: Access to fetch at &ap ...

Using ReactJS: Injecting components and passing variables in extended components without the need for functions

Currently, I am utilizing apollo for the authentication process in my nextJS application. My next task is to incorporate i18n support, but I am encountering some fundamental issues: The primary obstacle lies in handling class Index extends React.Component ...

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

Explore within the attribute of a JSON

Here is the JSON structure: var parse = [ { "variation_id":"34", "attributes":{ "attribute_pa_rozmiar":"m" }, "image_src":"http://localhost/Fraise-WP/wp-content/uploads/2013/06/Jellyfish-300x300.jpg", "image_l ...

Selector that targets an attribute in the beginning of its value [name^=value]

When trying to match input fields by name, I encountered a challenge. The names consist of a base name plus square brackets, which the PHP interpreter converts into arrays. According to the jQuery API, the suggested selector is as follows: ":input[name^=f ...

Using Node.js and Less to dynamically select a stylesheet source depending on the subdomain

Currently, my tech stack consists of nodejs, express, jade, and less. I have set up routing to different subdomains (for example: college1.domain.com, college2.domain.com). Each college has its own unique stylesheet. I am looking for a way to selectively ...

Encountered an error with AngularJS $http.post - Unexpected token F

I've encountered an issue while running my $http.post script and have been searching for a solution without success. Below is the error that appears when I try to run the webpage: XHR finished loading: POST "http://mypage/services/json/DownTimeStartB ...

Creating nested objects in JavaScript can be achieved by using the reduce method to return objects in an array

Looking to nest each element of an array into a new object within another object let newArr = ['Parent', 'Child'] Desiring the array to be transformed into this structure Parent[Child]={} Seeking a way to iterate through the array a ...

Verifying numerous route paths using Vue's dynamic binding (v-bind)

Currently, I am assigning a class to an li element depending on the route path using this code snippet: <li v-bind:class="{ 'current': $route.path == '/services' }"><nuxt-link to="/services">Services</ ...

Using React and graphql to show information on selected options across components

Currently, I'm facing a challenge in determining my next step. In productList.js, there is a straightforward select dropdown class component that displays all data from Products (id, name, brand,vintage) using graphql(apollo). It successfully sho ...

Is there a way to automatically execute this function when the React component is loaded, without the need for a button click?

After spending a few days trying to figure this out, I'm hitting a wall. This ReactJS project is new for me as I usually work with C#. The goal is to create a print label component that triggers the print dialog when a link in the menu is clicked. Cu ...

Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance: (function () { 'use strict'; angular.module("Dashboard") .controller("DashboardController", D ...

Error loading jakefile: Unable to load file

After attempting to use Jake, I encountered a strange issue where Jake was unable to load the Jakefile. Any suggestions on how to resolve this? Directory Structure: jake_test >> jake.sh jake_test >> jakefile.js jake.sh file node_modules/.b ...

Vue.js using the v-for directive with index

Just started using Vue.js and I have a question: I'm working with an array to create a table. When I double click on a table row, I want the program to execute a JavaScript function that will retrieve the selected item based on its index. <di ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

JQuery Challenge: Solving Dynamic Modal Issues

I'm in the process of creating a webpage that features multiple divs, each with its own unique image and title. Within each div, there's a button that, when clicked, should grab the specific image and title and display them in a modal. However, I ...

Utilizing Selenium JavaScript to insert a cookie into a request

Trying to add a cookie to the request in Selenium using JavaScript. I followed the documentation at this link, but my code snippet doesn't seem to pass any cookies to the PHP script below on the server. Here is the client-side JavaScript code: var w ...

Encountering a 403 status code from the Spotify Web API while attempting to retrieve data using an OAuth 2.0 Token

I'm currently experimenting with the Spotify Web API and attempting to retrieve my most played songs. To obtain an access token for making requests, I am utilizing the client credentials OAuth flow. While I have successfully obtained the access token, ...