Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
Javascript Algorithm to use for applying multiple discounts in a promotional sales event

We have a promo sales event on our store which is if you buy 1 Keyboard, you Get 20% off, if you Buy 2 Keyboards, Get 30% off, Buy 3 Keyboards, Get 40% off. Given the Keyboard's product price is USD 199.99. There is a maximum limit of only 6 keyboards where you can apply discount, if you buy more than that, no more additional discounts will be applied.

Can anyone help me to create an algorithm to apply the discount and to compute the total amount if customer buys 1 up to 6 or more of this specific product?

Buy 1 Keyboard  = 20% discount
Buy 2 Keyboards = 30% discount
Buy 3 Keyboards = 40% discount

This was the first code I tried to solve the our issue but I was getting incorrect results:

let cart = [];
let disc_amount;
let total_amount;

discFor1 = 0.2;
discFor2 = 0.3;
discFor3 = 0.4;
discFor4 = 0.6;
discFor5 = 0.7;
discFor6 = 0.8;

const keyboard = {
    id: "1001",
    name: "Yamaha PSR-E273 Keyboard",
    reg_price: 199.99,
    disc_price: 0
};


const addKeyboardToCart = () => {
    cart.push(keyboard);
};

const getDiscount = (cart) => {
    if (cart.length < 1) {
        console.log("Please add an item");
    }

    if (cart.length === 1) {
        disc_amount = keyboard.reg_price * discFor1;
    } else if (cart.length === 2) {
        disc_amount = keyboard.reg_price * discFor2;
    } else if (cart.length === 3) {
        disc_amount = keyboard.reg_price * discFor3;
    } else if (cart.length === 4) {
        disc_amount = keyboard.reg_price * discFor4;
    } else if (cart.length === 5) {
        disc_amount = keyboard.reg_price * discFor5;
    } else if (cart.length === 6) {
        disc_amount = keyboard.reg_price * discFor6;
    } else if (cart.length > 6) {
        disc_amount = keyboard.reg_price * discFor6;
    }

    return disc_amount;
};

const getTotalAmount = (disc_amount, cart) => {
    let total_reg_price_amount = 0;
    for (let i = 0; i < cart.length; i++) {
        total_reg_price_amount += cart[i].reg_price;
    }
    total_amount = total_reg_price_amount - disc_amount;

    return total_amount;
};

addKeyboardToCart();
addKeyboardToCart();
addKeyboardToCart();
addKeyboardToCart();
addKeyboardToCart();
addKeyboardToCart();

getDiscount(cart);

getTotalAmount(disc_amount, cart);

Edit: I'm also trying to implement how to get the best discount for the customer that's why I'm trying to apply the discount dynamically instead of hard-coding the discount amount for every number of items ordered.

Edit: I revised my question and removed additional questions so that the answers can focus more on a specific problem.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I simplified the problem a little bit but kept the same logic that you were following:

I also added small test function to test out the function for all the cases you want. I already added some. You can add more if you want.

Edited to Add : How to calculate totalPrice and also add more testcases

keyboard = {
  reg_price: 200
}
const discFor1 = 0.20
const discFor2 = 0.30
const discFor3 = 0.40
const getDiscount = (cart_length) => {
  switch ( cart_length ) {
    case 1 : return keyboard.reg_price * discFor1;
    case 2 : return keyboard.reg_price * 2 * discFor2;
    case 3 : return keyboard.reg_price * 3 * discFor3;
    case 4 : return keyboard.reg_price * 3 * discFor3 + keyboard.reg_price * discFor1;
    case 5 : return keyboard.reg_price * 3 * discFor3 + keyboard.reg_price * 2 * discFor2;
    default : return keyboard.reg_price * 6 * discFor3;
  }
};

const getTotalAmount = (cart) => {
  if (cart.length == 0) {
    console.log("Please add an item")
    return;
  }
    total_amount = cart.length * keyboard.reg_price - getDiscount(cart.length);
    return total_amount;
};

const test = ( cart, ans ) => {
  if ( getTotalAmount(cart) !== ans) {
    console.log(`Error: expected ${ans}, received ${getTotalAmount(cart)}`)
  } else {
    console.log(`Success: expected ${ans}, received ${getTotalAmount(cart)}`)
  }
}

test([], undefined)
test(["keybd"], 200 - 40)
test(["keybd", "keybd"], 400 - 120)
test(["keybd", "keybd", "keybd"], 600 - 240)
test(["keybd", "keybd", "keybd", "keybd"], 800 - 280)
test(["keybd", "keybd", "keybd", "keybd", "keybd"], 1000 - 360)
test(["keybd", "keybd", "keybd", "keybd", "keybd", "keybd"], 1200 - 480)
test(["keybd", "keybd", "keybd", "keybd", "keybd", "keybd", "keybd"], 1400 - 480)
test(["keybd", "keybd", "keybd", "keybd", "keybd", "keybd", "keybd", "keybd"], 1600 - 480)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda