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

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly. Within the DirectoryView ...

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

Introducing cutting-edge intellisense for Typescript Vue in VSCode, featuring automatic import functionality specifically designed for the

Currently, I am working on a small project using Typescript and Vue in VSCode. In my setup, I have TSLint, TSLint Vue, Vetur, and Prettier plugins installed. Unfortunately, I am facing an issue with the intellisense "auto import" feature. It does not seem ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

"Utilizing VueJS XHR functionality within a versatile and reusable component

Seeking advice on best practices for improving the following scenario: I have a single global reusable component called <MainMenu>. Within this component, I am making an XHR request to fetch menu items. If I place <MainMenu> in both the heade ...

Unit testing for changes in AngularJS $scope variables within the .then() function

I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope variable testable. I am assigning the variable within the .then() block of my controller and need to ensure it is set correctly when the . ...

What is the best way to navigate to the bottom of a page when new data is added?

I've created a chat feature in my Ionic app, but the issue is that when a user receives a new message while being on the chat screen, the view doesn't automatically scroll down to show the new message. The user has to manually scroll down to see ...

How can we simplify this React component to reduce its verbosity?

After creating a test project to delve into react, react-router and react-redux, I revisited the Settings.jsx file. Now, I am pondering on how to streamline it and reduce potential errors. import React, { Component } from "react"; import { connect } from ...

How to Access a Method from Controller 2 in AngularJS Controller One

angular.module('starter.controllers', []) .controller('controller1',function($scope) { $scope.function1= function () { // Code for controller1 function } }) .controller('controller2',fun ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

I am currently working on obtaining images that are saved by their URL within a PHP file. These images are located within a directory named "images."

My code is incomplete and not functioning as expected. $.get("museums.php",function(data,status){ var response=''; //console.log(data); var json = $.parseJSON(data); museums = json.museums; for(let m in museums) { $("#na ...

Is it possible for the ajax url option to accept an array of URLs rather than just one?

Is there a way to retrieve and store data from multiple JSON URLs in an array? <script type="text/javascript"> urls = ["https://spreadsheets.google.com/feeds/list/1RsiDuydBBHyu4OBjlxq1YH6yT3qcJDMB6-YKU-xxd_k/od6/public/basic?hl=en_US&alt=jso ...

The antithesis of a feature that encapsulates a chosen area with a span

Hi everyone, I have a function that works as follows: define(function () { 'use strict'; var sel, range, span; return function () { span = document.createElement("span"); span.className = 'highlight'; if (window.ge ...

Keeping the Bootstrap popover anchored to the content

I have a functional bootstrap popover that includes a time attribute. However, I am looking to enhance its functionality so that it remains open when the mouse is on the content and closes only when the mouse leaves the content. Here is the relevant code ...

Angular select automatically saves the selected option when navigating between views

I would like the selected option in my dropdown menu to stay selected as I navigate through different views and then return back. Here is the view: <select ng-model="selectedSeason" class="form-control" ng-options="season as 'Season '+ seas ...

Is it possible to automatically reload the previous link when the back button of the browser is clicked?

I am working on a website where the main content is loaded using jQuery Ajax based on the selected menu item. When a menu item is selected, the URL changes according to this pattern: http://host/domain/index.php?pageid=page In this scenario, the 'p ...

Unable to open new window on iOS devices using $window.open

alertPopup.then (function(res) { if(ionic.Platform.isAndroid()) { $window.open('android_link_here', '_system') } else if(ionic.Platform.isIOS()) { $window.open('ios_link_here', '_system& ...