Skip to content

E-commerce

E-commerce involves heavy price calculations where precision is critical.

Price Calculation

javascript
import { calc } from "a-calc";

const total = calc("price * quantity | =2", { price: 99.9, quantity: 3 });
// '299.70'

const bigTotal = calc("price * quantity | =2,", {
  price: 9999.99,
  quantity: 10,
});
// '99,999.90'

Shopping Cart Total

javascript
import { calc_sum } from "a-calc";

const cart = [
  { name: "Phone", price: 699, quantity: 1 },
  { name: "Earbuds", price: 199, quantity: 2 },
  { name: "Case", price: 9.9, quantity: 3 },
];

const cartTotal = calc_sum("price * quantity | =2,", cart);
// '1,126.70'

Discounts

Percentage Discount

javascript
const discounted = calc("price * 0.8 | =2", { price: 199 });
// '159.20'

const withDiscount = calc("price * discount | =2", {
  price: 199,
  discount: 0.85,
});
// '169.15'

Coupon (Spend X Save Y)

javascript
function calcWithCoupon(subtotal, threshold, reduction) {
  const meetCondition = calc(`${subtotal} >= ${threshold} | !n`);
  if (meetCondition) {
    return calc("subtotal - reduction | =2", { subtotal, reduction });
  }
  return calc("subtotal | =2", { subtotal });
}

calcWithCoupon(299, 200, 30); // '269.00'
calcWithCoupon(150, 200, 30); // '150.00'

Shipping

javascript
function calcShipping(weight) {
  const firstWeight = 1,
    firstPrice = 3,
    extraPrice = 2;
  if (calc(`${weight} <= ${firstWeight} | !n`)) {
    return calc("firstPrice | =2", { firstPrice });
  }
  return calc("firstPrice + (weight - firstWeight) * extraPrice | =2", {
    firstPrice,
    weight,
    firstWeight,
    extraPrice,
  });
}

calcShipping(0.5); // '3.00'
calcShipping(3.5); // '8.00'

Points Redemption

javascript
function calcWithPoints(subtotal, points, ratio = 100) {
  const maxDeduction = calc("points / ratio", { points, ratio });
  const deduction = Math.min(parseFloat(maxDeduction), parseFloat(subtotal));
  const usedPoints = calc("deduction * ratio | =0", { deduction, ratio });

  return {
    deduction: calc("deduction | =2", { deduction }),
    usedPoints,
    finalPrice: calc("subtotal - deduction | =2", { subtotal, deduction }),
  };
}

calcWithPoints(100, 5000);
// { deduction: '50.00', usedPoints: '5000', finalPrice: '50.00' }

Proportional Discount Distribution

javascript
import { calc, calc_sum } from "a-calc";

const items = [
  { name: "Item A", price: 100 },
  { name: "Item B", price: 200 },
  { name: "Item C", price: 300 },
];
const totalDiscount = 60;

const total = calc_sum("price", items);

const distributed = items.map((item) => {
  const ratio = calc("price / total", { price: item.price, total });
  const itemDiscount = calc("discount * ratio | ~5=2", {
    discount: totalDiscount,
    ratio,
  });
  const finalPrice = calc("price - itemDiscount | =2", {
    price: item.price,
    itemDiscount,
  });
  return { ...item, discount: itemDiscount, finalPrice };
});

Released under the MIT License