implement a discount and waive tax computation specifically for Canadian customers

I have encountered a problem while developing a POS application for a client in Canada. My issue lies in the tax calculation process, where I am unsure how to handle discounts and tax exemptions properly. Here is the scenario: I have 2 items - item 1 priced at $10 and item 2 priced at $2 (tax exempt). Before applying the tax rate of 13%, I need to apply a discount of $5 on the total bill. How can I correctly calculate the total amount of taxes after applying the discount?

The desired result is obtaining the tax amount after the discount has been applied. The tax rate is fixed at 13%.

Item 1: $10 Item 2: $2 (Tax Exempt)

Subtotal: $12 Discount: $5 Tax Amount: ?

Answer №1

Follow these steps to achieve the desired outcome:

  1. Arrange the items based on price, starting with the most expensive.
  2. Implement the discount onto the sorted list of items until no discount remains.
  3. Add up the prices of the sorted list to determine the discounted subtotal.
  4. Total up the prices of the taxable items in that list to calculate the taxable amount.
  5. Apply the tax rate to the taxable amount and combine it with the subtotal to obtain the final total.

const ITEMS = [
  { price: 2.00, taxExempt: true },
  { price: 10.00, taxExempt: false },
  { price: 8.25, taxExempt: false },
]
const DISCOUNT = 12
const TAX = 0.13

const applyDiscount = (items, discount) => {
  // Step 1️⃣ sort by price, from highest to lowest
  items = items.slice().sort((a,b) => b.price - a.price)

  // Step 2️⃣
  return items.map(item => {
    let price = item.price
    const itemDiscount = Math.min(price, discount) 
    if (itemDiscount > 0) {
      price -= itemDiscount
      discount -= itemDiscount
    }
    return { ...item, price, origPrice: item.price, itemDiscount }
  })
}

const itemsWithDiscount = applyDiscount(ITEMS, DISCOUNT)
const sumPrices = arr => arr.map(x => x.price).reduce((p,c) => p + c, 0)
const subtotal = sumPrices(itemsWithDiscount) // Step 3️⃣
const taxableAmt = sumPrices(itemsWithDiscount.filter(x => !x.taxExempt)) // Step 4️⃣
const total = subtotal + (taxableAmt * TAX) // Step 5️⃣

console.log('items after discount', itemsWithDiscount)
console.log('subtotal: $' + subtotal.toFixed(2) + ' (taxable: $' + taxableAmt.toFixed(2) + ')')
console.log('tax: $' + (taxableAmt * TAX).toFixed(2) + ' (' + (TAX * 100) + '%)')
console.log('total: $' + total.toFixed(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

Should a checkbox be added prior to the hyperlink?

html tags <ul class="navmore"> <li><a href="link-1">Link 1</a></li> <li><a href="link-2">Link 2</a></li> </ul> Jquery Implementation in the footer $(".navmore li a").each(function(){ v ...

Incorporated new code into the website, functioning properly, although it appears to keep scrolling endlessly below the footer

My website is experiencing a strange issue where the page seems to keep extending beyond the footer due to some JS code. I am not very familiar with JavaScript and have tried different solutions without success. I have searched extensively online for a so ...

It is important for the button size to remain consistent, regardless of any increase in text content

My goal was to keep the button size fixed, even as the text on it grows. This is the current code I am using: .button { border: none; color: white; padding: 10px 50px; text-align: center; text-decoration: none; display: inline-block; font ...

NextJS is throwing an error stating that the function file.endsWith is not recognized as a valid

After upgrading from nextJS version 9.x.x to 12.x.x, I encountered the following error. Any assistance would be greatly appreciated. TypeError: file.endsWith is not a function at eval (webpack-internal:///./node_modules/next/dist/pages/_document.js ...

The process of efficiently uploading a batch of images to Firebase storage while also obtaining all the respective

I have been using firebase storage to upload images and save their respective URLs in the firebase database. However, I recently encountered an issue with my code. In firebase v8, everything was working fine, but after updating to version 9, the following ...

Maintaining the order of elements in Angular's insertion process

I am currently facing an issue with my HTML fragment that iterates over a key and value collection. Everything works perfectly when I insert values into an object and iterate through it using the HTML fragment. However, in order to maintain a specific key ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

What steps can be taken to resolve the issue of "Access Denied: Invalid token, incorrect code"?

Assigned to me recently for a school project is a coding challenge that consists of various parts. The final task involves uploading to a private GitHub repository and submitting a completion request through a POST request under specific conditions. I hav ...

Are you looking for outcomes related to Bootstrap typeahead feature?

I am facing an issue with returning results for the bootstrap typeahead after making an ajax request. Strangely, it works fine without initiating the ajax request. The code that doesn't work: $(".typeahead").typeahead({ source: function(query, pr ...

Issue with redeployment on render.com, Nuxt Encountered Fatal Error

The recent update was successfully pushed to Github, but the redeploy on the hosting platform is encountering errors that I can't quite identify. I followed the suggestion in the error message and ran npm rebuild, but it didn't resolve the issue. ...

How can I ensure a successful redirect to react-router root path after saving to MongoDB in Express?

As a newcomer to React and react-router, I may be making some rookie mistakes in my project. Currently, I am constructing a web application with React and react-router as the frontend server, paired with Express and MongoDB for the backend. To communicate ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

My goal is to design a dynamic textbox for a website that allows users to customize the text in any format they desire

I want to create a versatile textbox on my website that allows users to change the text format as they desire. Unfortunately, I am facing some issues with implementing this feature. Here is the code I have developed so far. <body> <h1>< ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...

Error Handling with Firebase Cloud Firestore and State Management in Vue using Vuex (firebase.firestore.QuerySnapshot)

Upon examining the code, I noticed an issue with docChanges. It seems to be a function, but when I try to use docChanges().doc.data().userId, I encounter the error message: store.js?3bf3:21 Uncaught TypeError: Cannot read property 'doc' of undefi ...