Problem overview
A shopper types a coupon code, and the program has to take the matching amount off the subtotal. The starter defines subtotal (100), the typed coupon ("SAVE20") and a lookup table coupons of type Record<string, number> that maps each valid code to its discount: SAVE10 to 10, SAVE20 to 20 and SAVE50 to 50.
The program computes total = subtotal - discount, stores the text Total: $80 in result and prints it. An unknown code takes nothing off: with a code that isn't in the table, the output is Total: $100.
Approach: look the code up, default to zero
One way to find a discount is a chain of comparisons, if (coupon === "SAVE10") ... else if (coupon === "SAVE20") .... It works, but every new coupon means new code. An object keyed by coupon code turns the problem into a lookup: coupons[coupon] goes straight to the value, however many coupons there are, and adding a coupon means adding one entry to the data.
The one subtlety is the missing key. Reading a property that doesn't exist doesn't raise an error in JavaScript or TypeScript. It gives undefined. So the code has to check for undefined and substitute 0 itself. A ternary expression does that in one line: coupons[coupon] !== undefined ? coupons[coupon] : 0 means "if the code has an entry, use it; otherwise use 0".
Because the lookup result decides the discount, and the discount decides the total, the three values are computed in that order: discount, then total, then the text.
Step by step
- Compute
discountas aconstnumber. Comparecoupons[coupon]withundefinedin a ternary. The first branch reads the value, the second gives 0. - Compute
total: the subtotal minus the discount. - Build
result: the fixed textTotal: $followed bytotal. The+operator converts the number to text. - Print
resultwithconsole.log.
The solution in TypeScript
const subtotal: number = 100;
const coupon: string = "SAVE20";
const coupons: Record<string, number> = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50};
const discount: number = coupons[coupon] !== undefined ? coupons[coupon] : 0;
const total: number = subtotal - discount;
const result: string = "Total: $" + total;
console.log(result);
Things to know about this code:
Record<string, number>is the type of an object whose keys are strings and whose values are numbers. It exists only for the compiler. At run timecouponsis an ordinary object.- The type says
number, but a missing key still givesundefined. With the lesson's compiler settings,coupons["BOGUS"]is typed as a number, so the compiler will not warn you. The!== undefinedcheck is what keeps the program correct. - Keys are case-sensitive. With the code
save20in lower case the lookup finds nothing and the output isTotal: $100. - Shorter forms exist.
coupons[coupon] ?? 0gives the same answers here: the??operator replaces onlyundefinedandnull. Don't use||for this job, because it would also replace a legitimate discount of 0. With a table entry{"FREE0": 0},||with a default of 99 gives 99, while??keeps the 0.
Edge cases and common mistakes
- Unknown code.
coupons["BOGUS"]isundefined. Without the check,100 - undefinedisNaNand the output would beTotal: $NaN. - Inherited property names. An object literal inherits properties such as
toStringandconstructor. If a shopper typestoStringas the code,coupons["toString"]is a function, which is notundefined, so the lesson's check accepts it as a discount and the program printsTotal: $NaN. The same applies to theinoperator. When codes come from untrusted input,Object.hasOwn(coupons, coupon)tests only the object's own keys, and aMapavoids the problem entirely:m.get("toString") ?? 0is 0. - A discount larger than the subtotal. The lesson doesn't clamp the total. With a subtotal of 30 and the code
SAVE50, the output isTotal: $-20. Real shops usually stop the total at 0 withMath.max(0, ...). - Calling the object like a function. Lookup uses square brackets,
coupons[coupon], not parentheses.
Testing
Change coupon in the editor above and compare with these results from the reference solution:
| coupon | output |
|---|---|
SAVE20 | Total: $80 |
BOGUS | Total: $100 |
save20 | Total: $100 |
toString | Total: $NaN |
