Why patterns matter for safety in Typescript - Performance Analysis
When we write code, certain patterns repeat many times. Understanding how these patterns affect the time it takes for code to run helps us keep programs safe and efficient.
We want to know how the work grows as the input gets bigger, so our code stays reliable and fast.
Analyze the time complexity of the following code snippet.
function checkPattern(arr: number[]): boolean {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 0) {
return true;
}
}
return false;
}
This code checks if the number 0 appears anywhere in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to the length of the array, stopping early if 0 is found.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The code always checks every item no matter what."
[OK] Correct: The code stops early when it finds 0, so sometimes it does less work than the full array length.
Knowing how patterns like loops affect time helps you explain your code clearly and shows you understand how to keep programs safe and efficient.
"What if we changed the code to check for every zero and count them instead of stopping early? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of patterns in TypeScript
Patterns guide how to write code that avoids common mistakes and bugs.Step 2: Identify the benefit of safety patterns
They help detect errors early, before the program runs, improving reliability.Final Answer:
They help catch errors before running the code -> Option DQuick Check:
Patterns catch errors early = A [OK]
- Thinking patterns only improve speed
- Believing patterns reduce file size
- Assuming patterns skip type checks
value is a string before using it?Solution
Step 1: Recall correct type checking syntax in TypeScript
Usetypeof variable === 'string'to check if a variable is a string.Step 2: Evaluate each option
Only if (typeof value === 'string') { /* use value */ } uses the correcttypeofoperator and string comparison.Final Answer:
if (typeof value === 'string') { /* use value */ } -> Option AQuick Check:
Use typeof for type checks = D [OK]
- Using .type property which doesn't exist
- Using instanceof with string literal
- Comparing variable directly to string keyword
function safeDivide(a: number, b: number): number | null {
if (b === 0) return null;
return a / b;
}
console.log(safeDivide(10, 2));
console.log(safeDivide(10, 0));Solution
Step 1: Analyze the function safeDivide
If divisorbis zero, function returnsnull, else returns division result.Step 2: Evaluate console.log outputs
First call: 10 / 2 = 5; second call: divisor is 0, returns null.Final Answer:
5 and null -> Option AQuick Check:
Division by zero returns null = C [OK]
- Expecting division by zero to return 0
- Assuming runtime error instead of null
- Confusing null with Infinity
interface User {
name: string;
age?: number;
}
function getUserAge(user: User): number {
return user.age;
}Solution
Step 1: Understand optional property in interface
Propertyageis optional, so it may be undefined.Step 2: Check function return type vs possible undefined
Function returnsnumberbutuser.agecan be undefined, causing a type error.Final Answer:
Missing check for optional property before returning -> Option BQuick Check:
Optional properties need checks = A [OK]
- Ignoring optional property may be undefined
- Thinking interface syntax is wrong
- Confusing return type with property type
const items = ["apple", 42, "banana", null, "cherry"];
// Which pattern is safest to create { [key: string]: number } mapping?Solution
Step 1: Identify the need to filter only strings
Since array has mixed types, filter out non-string values to avoid errors.Step 2: Map filtered strings to their lengths safely
After filtering, create object entries mapping strings to their length, ensuring type safety.Final Answer:
Use a filter to keep only strings, then map to lengths -> Option CQuick Check:
Filter then map for safe transformation = B [OK]
- Mapping without filtering causes runtime errors
- Using loops without type checks
- Assigning mixed types directly to object keys
Ready to prove it?
Pass the test and this pattern moves unknown
