Webux Lab

By Studio Webux

NodeJS script to calculate pricing

TG
Tommy Gingras Studio Webux 2022-04-06

Simple NodeJS script to calculate range pricing and discount

This nodejs script uses an array with a defined range and price. To determine the final price.

For example, To charge at discounted price when your users order more, you can use this kind of approach.


The script

rules: you can specify the minimum and maximum quantity. Then specify the price per item within that range. clients: Then a simple array to run some estimates. You can update this script to fit your requirements.

const rules = [
  {
    min: 0,
    max: 1,
    price: 0,
  },
  {
    min: 2,
    max: 10,
    price: 4,
  },
  {
    min: 11,
    max: 20,
    price: 3,
  },
  {
    min: 21,
    max: 50,
    price: 2,
  },
  {
    min: 51,
    max: Infinity,
    price: 1,
  },
];

const clients = [
  // 700
  {
    qt: 8,
    count: 25,
  },
  // 600
  {
    qt: 4,
    count: 50,
  },
  // 730
  {
    qt: 25,
    count: 10,
  },
  // 615
  {
    qt: 12,
    count: 15,
  },
  // 790
  {
    qt: 88,
    count: 5,
  },
];

// Total monthly revenue
let monthlyRevenue = 0;

// For each estimates
clients.forEach((client) => {
  // Set the current client to 0
  let clientRevenue = 0;
  // To avoid updating the value of the array we are keeping track of the updated value that way.
  let remaining = client.qt;

  // Check the remaining quantity to apply the correct price
  rules.forEach((rule) => {
    // If nothing to check, simply return
    if (remaining === 0) return;
    // If the min or max match, update the remaining quantity and apply the price with the correct qauntity using the price of the rule.
    if (client.qt > rule.min || client.qt < rule.max) {
      let qt = rule.max - rule.min;
      if (remaining - qt > 0) {
        remaining -= qt;
      } else {
        qt = remaining;
        remaining = 0;
      }
      clientRevenue += qt * rule.price * client.count;
    }
  });
  
  // Increase the monthly price
  monthlyRevenue += clientRevenue;
  console.debug(
    `Client revenue [${client.count} client(s) x ${
      client.qt
    } item(s)] ${clientRevenue}$/month (${(
      clientRevenue /
      (client.qt * client.count)
    ).toFixed(2)}$ per item)`,
  );
});

console.debug(
  'Monthly Revenue:',
  monthlyRevenue,
  '$ yearly:',
  monthlyRevenue * 12,
  '$',
);


Output

Client revenue [25 client(s) x 8 item(s)] 700$/month (3.50$ per item)
Client revenue [50 client(s) x 4 item(s)] 600$/month (3.00$ per item)
Client revenue [10 client(s) x 25 item(s)] 730$/month (2.92$ per item)
Client revenue [15 client(s) x 12 item(s)] 615$/month (3.42$ per item)
Client revenue [5 client(s) x 88 item(s)] 790$/month (1.80$ per item)
Monthly Revenue: 3435 $ yearly: 41220 $

Search