Back to js-conditionals
06-shipping-calculator.js
JavaScript
1/**
2 * 📦 ShopSwift Shipping Calculator
3 *
4 * ShopSwift is a growing online store. They've hired you to build their
5 * shipping cost calculator. The cost depends on the package weight,
6 * where it's going, and the order total.
7 *
8 * Domestic Shipping (country === "US"):
9 * - Weight up to 1 kg: $5
10 * - Weight up to 5 kg: $10
11 * - Weight over 5 kg: $15
12 *
13 * International Shipping (any other country):
14 * - Weight up to 1 kg: $15
15 * - Weight up to 5 kg: $25
16 * - Weight over 5 kg: $40
17 *
18 * Free Shipping:
19 * - Domestic orders over $50 get FREE shipping (return 0)
20 * - International orders over $100 get FREE shipping (return 0)
21 *
22 * Rules:
23 * - If weight is 0 or negative, return -1
24 * - If orderTotal is negative, return -1
25 *
26 * @param {number} weight - Package weight in kilograms
27 * @param {string} country - Destination country code (e.g., "US", "UK", "IN")
28 * @param {number} orderTotal - Total order amount in dollars
29 * @returns {number} Shipping cost, 0 for free shipping, or -1 for invalid input
30 */
31export function calculateShipping(weight, country, orderTotal) {
32 if (weight <= 0) {
33 return -1
34 }
35 if (orderTotal < 0) {
36 return -1
37 }
38
39 let shippingCost
40 if (country == "US") {
41 if (weight <= 1) {
42 shippingCost = 5
43 } else if (weight <= 5) {
44 shippingCost = 10
45 } else {
46 shippingCost = 15
47 }
48 } else {
49 if (weight <= 1) {
50 shippingCost = 15
51 } else if (weight <= 5) {
52 shippingCost = 25
53 } else {
54 shippingCost = 40
55 }
56 }
57
58 if (country == "US" && orderTotal > 50) {
59 return 0
60 }
61 if (country !== "US" && orderTotal > 100) {
62 return 0
63 }
64
65 return shippingCost
66}
67