Streamlined JavaScript function with code that closely mirrors the original version

Hey there, I'm currently developing an app that simulates pricing. Below is a snippet of the code I am working on:

  function calculatePrice(x) {
     if (x >= '1' && x <= '50') {
         var sum = (120 * x);
         hasil.value = 'Rp.' + parseFloat(sum * 1000);
     } else if (x >= '51' && x <= '100') {
         var sum = (115 * x);
         hasil.value = 'Rp.' + parseFloat(sum * 1000);
     } else if (x >= '101' && x <= '200') {
         var sum = (110 * x);
         hasil.value = 'Rp.' + parseFloat(sum * 1000);
     } else {
         hasil.value = 'error!';
     }
 }

 

I have multiple functions like this and I am looking for a way to simplify it into just one function. Is it possible?

Answer №1

Give it a shot:

  function calculateTotalPrice(quantity, maxval) {
    if (quantity >= '1' && quantity <= '50') {
      var total = (maxval + 10) * quantity;
      result.value = 'Rp.' + parseFloat(total * 1000);
    }
     else if (quantity >= '51' && quantity <= '100') {
       var total = (maxval + 5) * quantity;
       result.value = 'Rp.' + parseFloat(total * 1000);
     }
     else if (quantity >= '101' && quantity <= '200') {
       var total = maxval * quantity;
       result.value = 'Rp.' + parseFloat(total * 1000);
     }
     else {
       result.value = 'error!';
     }
  }

Just to clarify, I am assuming that the increment value for maxval is 5. If more information is provided, a more accurate solution can be presented.

Answer №2

Here's how I would approach this task. While I may have a different perspective on handling integers, coding style is subjective. I prefer passing in an object containing the necessary values rather than duplicating logic. Although some might frown upon monkeypatching String, it serves the purpose in this scenario where variable x is assumed to be a string.

String.prototype.isWithinRange = function(lower, upper){
  const int = parseInt(this)
  return int >= parseInt(lower) && int <= parseInt(upper)
}

const range120 = {0: 120, 1: 115, 2: 110}
const range125 = {0: 125, 1: 120, 2: 115}
function calculateMax(x, values) {
  let total
  hasil.value = ''
  if (x.isWithinRange('1', '50')) {
    total = values['0'] * x
  } else if (x.isWithinRange('51', '100')) {
    total = values['1'] * x
  } else if (x.isWithinRange('101', '200')) {
    total = values['2'] * x
  } else {
    hasil.value = 'error'
  }
  hasil.value = hasil.value ? 'error' : 'Rp.'+parseFloat(total*1000);
}

Answer №3

function calculateTotal(x, extra) {
  var totalAmount = extra;
  if(x >= '1' && x <= '50'){
   totalAmount += 120;
  }
  else if (x >= '51' && x <= '100'){
   totalAmount += 115;
  }
  else if(x >= '101' && x <= '200'){
   totalAmount += 110;
  }

  if(x < 1 && x > 200){
    output.value = 'error!';
  } else {
    output.value = 'Rp.'+parseFloat((totalAmount) * x *1000);
  }
}

The extra parameter can be set as 0 or 5 for the functions max110 or max115

Answer №4

Essentially, you are dealing with two functions that operate in the same manner and produce similar outcomes with varying values.

  • The distinct values can be stored in an array, allowing for the use of a single function to retrieve the index and fetch the corresponding value from the array based on that index.

  • Therefore, it is crucial to organize the variables types effectively. If a variable is intended to be used as a number, then it should strictly be treated as a number. This also applies to comparisons, where both sides of the condition should involve numbers.

  • Opt for a pure function that does not modify any external state, which means all necessary data should be provided to the function explicitly.

  • Incorporate checks within the function to handle unwanted values and terminate early if needed. A preliminary check at the lower boundary, such as zero or below, can directly return -1 since it doesn't correspond to a valid array index (resembling the behavior of Array#indexOf).

  • Similarly, perform an early exit by checking against the upper boundary without requiring additional else if structures.

  • Lastly, ensure to return -1 when the index is not found upon completion.

Summarized:

function getValue(x, maxArray) {
    var index = getIndex(x);
    if (index in maxArray) {
        return 'Rp.' + maxArray[index] * x * 1000;
    }
    return 'error!';
}

function getIndex(x) {
    if (!x || x < 0) {
        return -1;
    }
    if (x <= 50) {
        return 0;
    }
    if (x <= 100) {
        return 1;
    }
    if (x <= 200) {
        return 2;
    }
    return -1;
}

var max110 = [120, 115, 110],
    max115 = [125, 120, 115];

console.log(getValue(-1, max110));
console.log(getValue(10, max110));
console.log(getValue(10, max115));

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

Is it possible to transfer a file or folder to a different location within the Google Drive API?

After following the instructions in the documentation found here, my code still isn't functioning correctly. I made some adjustments to the script: window.gapi.client.drive.files.get({ fileId: fileId, fields: 'parents' ...

Modal containing Jquery GalleryView

I am facing an issue with loading galleryView inside a modal. Even though using galleryView on its own works fine, I have been unable to make it work within a modal. Despite looking for solutions in previous posts, I couldn't find anything that fixed ...

Sending JavaScript variables to an ArrayList in a Java servlet

For instance, Let's say we have the following table: <table> <tr> <td>john</td> <td>doe</td> </tr> </table> This table can be dynamically generated. I am extracting values from the table using this ...

Retrieve the data stored in a concealed input field within a specific row of a table

I am dealing with an automatically generated table that is populated with data from a database and built using jQuery. The table is created by appending the following tr variable to the main tbody section of the HTML code: Below you can find my code snippe ...

I am looking to extract the content of the title within an HTML table

Check out my code snippet below: <td class="text-left"><div class="ettn" data-toggle="tooltip" title="7f5e5b03-7d30-4001-acd9-c993d6c24301">ETTN</div></td> I am looking to extract the value ...

Tips for adding an active class when a link is clicked

I am working on a Sidebar component and need to apply the active_class_link style to the DIV element when the onClick() event occurs. Although I have set up the function, I am unsure how to apply this for each DIV within my component. The desired behavior ...

Is utilizing the correct use case for a Bunyan child logger?

I've recently started exploring bunyan for logging in my nodejs application. After giving it a try, everything seems to be functioning quite smoothly. Initially, I overlooked a section on log.child, but now I am eager to understand its usage. It appea ...

Transmitting data in JSON format via a RESTful API

I am working on generating the following structure: [ { "id":"1", }, { "id":"3", }, { "id":"5", }, { "id":"6", }, { "id":" ...

Display a notification when the browser is being closed, but refrain from showing the notification when the closure is due to logging off

When a user logs out of my application, the browser closes and triggers an alert. I want the alert to appear only when the browser is directly closed, not when it's closed through the logout process, where a different confirm message is shown. functi ...

Is there a way to configure the bootstrap datetimepicker to only allow selection of time

I am having trouble using bootstrap datetimepicker with the initialization code like this: $('#departure-time').datetimepicker({ todayHighlight: true, autoclose: true, format: 'yyyy-mm-dd hh:ii' }).on('change' ...

The second request made with $.ajax is bypassed

I have been working on integrating the Google Maps JavaScript API and attempting to update a heat map when a user clicks on a specific div element. The latitude and longitude data used for the heatmap are fetched from local JSON files. While I have success ...

Is there a way to include the ID of the currently logged-in user when making a call to axios.get in react-redux?

I'm a beginner in react-redux, working on an Express app with react as the frontend and redux store concept. I need to pass the logged-in user as a parameter in my axios.get method. How can I achieve this? So far, I've been retrieving the user._ ...

Form with dynamic input fields - starting values

I'm having trouble setting initial values for the antd dynamic form. Is there a way to initialize values in a dynamic form without registering the field using getFieldDecorator first? The error message I'm receiving is "You cannot set field befor ...

The page transition on Android lacks fluidity

Currently, I am working on developing a hybrid app with HTML5 and AngularJS. One of the features I have incorporated is the use of Angular animate for page transitions. However, I have noticed that while the transition is seamless on iOS devices, there s ...

When there are numerous websocket connections in Google Chrome, Socket.io can encounter issues and break down

I am encountering an issue where I create 60 client connections to a socket.io server using Google Chrome browser. The server sends screenshots to the clients at specific times, but some of the websocket connections, which are subprotocols of socket.io, ge ...

What is the best way to select and link a specific section of a string using Javascript?

I have a JavaScript string that looks like the following: const pageContent = "He stood up and asked the teacher, "Can you elaborate the last point please?"; My goal is to map out the words in the string and display them in a way that makes ...

Leveraging the power of dual layouts in Nuxt 3

I've encountered an issue with my /profile page setup. It utilizes a profile layout for common elements like the sidebar, but I also have a sub-page at /profile/favorite. My goal is to incorporate both the default layout (with a header and footer) and ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

Selenium javascript is displaying error codes when trying to retrieve console logs

Below is the code snippet I'm using in Selenium with JavaScript. In the final step, I want to retrieve any error codes from the browser console and specifically check for the absence of any 504 error codes on the current page. driver.get(M_URL) .t ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...