Created
November 14, 2017 18:08
-
-
Save wzulfikar/6dccb2d591912d6ca8586788041b567c to your computer and use it in GitHub Desktop.
Using TypeScript to create order summary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wed, 15 Nov 2017 at 0:56:13 MYT | |
* "Using TypeScript to create order summary." | |
* | |
* The purpose of this snippet is to demonstrate the | |
* use of TypeScript in our code. | |
* You can run this code online here: | |
* https://www.typescriptlang.org/play/ | |
* | |
* PS: | |
* The code is based on Fun Fun Function (@mpjme), | |
* Unit testing in JavaScript Part 1 | |
* https://www.youtube.com/watch?v=Eu35xM76kKY | |
* | |
**/ | |
interface IOrderItem { | |
name: string; | |
price: number; | |
shipppingCost?: number; // TS: use `?` to indicate optional property | |
} | |
interface IOrder { | |
// [TRY THIS] | |
// using VSCode, hover on `IOrderItem` below | |
// and hold `option` key (OSX) to display symbol definition | |
items: Array<IOrderItem>; | |
} | |
interface IOrderSummary { | |
itemsCount: number; | |
totalPrice: number; | |
} | |
const orderSummary = (order: IOrder): IOrderSummary => { | |
const initialValue: number = 0; // ← [TRY THIS] change `number` to `string` and see the error | |
const totalPrice: number = order.items.reduce( | |
(prev: number, current: IOrderItem): number => { | |
// [CHALLENGE] convert this return statement into ES6 "Implicit Return Shorthand" | |
return prev + current.price + (current.shipppingCost || 0); | |
}, | |
initialValue | |
); | |
return { | |
itemsCount: order.items.length, | |
totalPrice // ← use ES6 property-value shorthand | |
}; | |
}; | |
// [TRY THIS] change `IOrder` to other type and see the error | |
const sampleOrder: IOrder = { | |
items: [ | |
{ | |
name: "Penetration Tester's Open Source Toolkit", | |
price: 100, | |
shipppingCost: 21 | |
}, | |
{ | |
name: "Gray Hat Hacking Second Edition", | |
price: 250 | |
// notice that it's *safe* to not put `shippingCost` here | |
// because we declared it as optional in interface `IOrderItem` | |
} | |
] | |
}; | |
const summary = orderSummary(sampleOrder); | |
// sample of test case | |
console.log(summary, summary.totalPrice == 371 ? "✔ PASSED" : "✘ FAILED"); | |
console.log(summary, summary.totalPrice != 370 ? "✔ PASSED" : "✘ FAILED"); | |
// ---------------------------- | |
// | |
// Bonuses: | |
// 1. command to re-run this file on save: | |
// → `nodemon --watch '*.ts' --exec 'ts-node' orderSummary.ts` | |
// 2. Article about JS shorthand techniques: | |
// → https://www.sitepoint.com/shorthand-javascript-techniques/ | |
// | |
// ---------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment