Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword.

if (Math.random() * 100 < 100 / (19.37 / NewData.PriceDivider)) {
        Rarity = Rarities.uncommon;
        Embed.addField("Rarity", Rarity, true);
        Embed.setColor("GREEN");
} else if (Math.random() * 100 < 100 / (5.18 / NewData.PriceDivider)) {
        Rarity = Rarities.common;
        Embed.addField("Rarity", Rarity, true);
        Embed.setColor("GREY");
} else if (Math.random() * 100 < 100) {
        Rarity = Rarities.basic;
        Embed.addField("Rarity", Rarity, true);
        Embed.setColor("GREY");
}

Answer №1

One way to make the code more concise is by using a ternary operator instead of rewriting assignment statements:

let randomValue = Math.random() * 100
const firstCondition = 19.37 / NewData.PriceDivider
const secondCondition = 19.37 / 100 / (5.18 / NewData.PriceDivider)

// Handle the case where randomValue === 100: if (randomValue === 100) // do something

Rarity = randomValue < firstCondition ? Rarities.uncommon : randomValue < secondCondition ? Rarities.common : Rarities.basic
Embed.addField("Rarity", Rarity, true);
Embed.setColor(randomValue < firstCondition ? "GREEN" : "GREY");

If you need to handle the scenario when Math.random() generates 1, it might be best to address that outside of this specific block of code.

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

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

Best practice for saving a User object to the Request in a Nest.js middleware

Currently, in my nest.js application, I have implemented a middleware to authenticate Firebase tokens and map the user_id to my database. Within this middleware, I retrieve the user_id from Firebase, fetch the corresponding User object from the database, a ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

The count of records in MongoDB by the current month

Recently delving into MongoDB, I found myself in need of a way to retrieve the count of posts made in the current month. Keeping timestamps true in my PlateModel model, it appears as follows: { timestamps: true } The current code snippet in my Controller ...

Fulfill the promise within the $stateProvider and proceed with utilizing the outcomes

I am facing an issue where I need to resolve a promise in a state provider so that I can use the results of the promise in another promise. I am a bit unsure about how to go about this. I tried the following approach: app .config(['$stateProvid ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

Unexpected behavior: custom event firing multiple times despite being emitted only once

I am utilizing the ws module for incorporating web sockets functionality. An event named newmessage seems to be triggering multiple times in correlation with the number of active sockets connected to the web-socket-server. The scenario puzzled me initiall ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

jQuery is missing an essential component that is causing an error

I have successfully implemented the following JavaScript code and everything is working fine. However, I'm uncertain if my code is fully correct. I noticed that in my script, I only utilize success: function() without incorporating an error function. ...

Different tsconfigs assigned to various directories

In my project, I am using Next.js with TypeScript and Cypress for E2E tests. The challenge I am facing is configuring tsc to handle multiple configs for different folders. The tsconfig.json file in the project root for Next.js looks like this: { "c ...

Encountering issues while attempting to upload items to AWS S3 bucket through NodeJS, receiving an Access Denied error 403

I encountered an issue while attempting to upload objects into AWS S3 using a NodeJS program. 2020-07-24T15:04:45.744Z 91aaad14-c00a-12c4-89f6-4c59fee047a1 INFO uploading to S3 2020-07-24T15:04:47.383Z 91aaad14-c00a-12c4-89f6-4c59fee047a1 IN ...

Error connecting to Firebase Cloud Functions - connection issue

Whenever I call my cloud function, I see the following message in the logs: Function execution took 5910 ms, finished with status: 'connection error'. It seems to be related to promises and returning or !d.exists, but I haven't been able to ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

Error in TypeScript React: 'Display' property is not compatible with index signature

My design page in React with TypeScript template is using Material UI, with custom styles implemented using the sx prop of Material UI. To customize the styling, I have created a separate object for the properties related to the sx props: const myStyles = ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Using TypeScript generics with the `keyof` operator may result in rejection

I created a custom method using the RXJS library which looks like this : function Subject<T>(t: T):T { return t; } In addition, I defined an interface that specifies the structure of my application values. Additional keys can be added to this i ...

`Animate your divs with slide in and slide out effects using

Currently, I am in the process of replicating a website and facing some challenges. This site is my inspiration for the project. I have managed to create a sliding effect using CSS, making the div slide in and out from the same direction. However, I want ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

Re-establishing the socket channel connection in a React application after a disconnection

There are several solutions to this issue, but none of them seem to be effective for me. The existing solutions are either outdated or do not meet my needs. I am facing a problem where I have a large amount of data being transferred from the server to the ...