An educational pure functional programming library in TypeScript
2
fork

Configure Feed

Select the types of activity you want to include in your feed.

Refactor tutorial chapter 1 divide() to ternary expression

+5 -4
+5 -4
docs/guides/tutorial/01-why-functional-typescript.md
··· 25 25 26 26 ```typescript 27 27 const divide = (a: number, b: number): number => { 28 + // This function lies about its type - it can throw! 28 29 if (b === 0) throw new Error("Division by zero") 29 30 return a / b 30 31 } ··· 38 39 const processOrder = async (orderId: string): Promise<Order> => { 39 40 const order = await db.findOrder(orderId) // Throws if not found 40 41 const user = await db.findUser(order.userId) // Throws if not found 42 + 41 43 await payment.charge(user, order.total) // Throws if declined 42 44 await inventory.reserve(order.items) // Throws if out of stock 43 45 await email.send(user.email, "Order confirmed") // Throws if invalid email 46 + 44 47 return order 45 48 } 46 49 ``` ··· 60 63 What if errors were part of the return type? 61 64 62 65 ```typescript 63 - const divide = (a: number, b: number): Result<number, DivisionError> => { 64 - if (b === 0) return err({ _tag: "DivisionByZero" }) 65 - return ok(a / b) 66 - } 66 + const divide = (a: number, b: number): Result<number, DivisionError> => 67 + b === 0 ? err({ _tag: "DivisionByZero" }) : ok(a / b) 67 68 ``` 68 69 69 70 Now the type tells the truth. This function returns either: