Declaring functions and classes in Typescript - Time & Space Complexity
When we declare functions or classes, we want to know how much time it takes to create them as the program grows.
We ask: Does making more functions or classes slow down the program, and by how much?
Analyze the time complexity of the following code snippet.
function greet(name: string) {
return `Hello, ${name}!`;
}
class Person {
constructor(public name: string) {}
sayHello() {
return greet(this.name);
}
}
const people = [new Person('Alice'), new Person('Bob')];
people.forEach(p => console.log(p.sayHello()));
This code declares a function and a class, creates two objects, and calls a method on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forEachloop that callssayHelloon each person. - How many times: Once for each person in the
peoplearray.
Each person in the list causes one call to sayHello, which calls greet.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to sayHello and greet |
| 100 | 100 calls to sayHello and greet |
| 1000 | 1000 calls to sayHello and greet |
Pattern observation: The number of calls grows directly with the number of people.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more people.
[X] Wrong: "Declaring a function or class takes a lot of time every time it is used."
[OK] Correct: Declaring happens once when the code loads, not each time you call the function or create an object.
Understanding how function and class declarations affect performance helps you write clear and efficient code, a skill valued in many coding challenges.
"What if we created 1000 objects but only called sayHello on 10 of them? How would the time complexity change?"
Practice
Solution
Step 1: Understand what a function does
A function is a block of code designed to perform a specific task.Step 2: Recognize the role of return values
Functions can return results after performing their task, making them reusable.Final Answer:
To perform a specific task and optionally return a result -> Option CQuick Check:
Function purpose = perform task + return result [OK]
- Confusing functions with variables
- Thinking functions only store data
- Believing functions cannot return values
greet that takes a string name and returns a string in TypeScript?Solution
Step 1: Check function parameter and return types
function greet(name: string): string { return `Hello, ${name}`; } correctly declares the parameternameas a string and the return type as string.Step 2: Verify function body returns a string
function greet(name: string): string { return `Hello, ${name}`; } returns a template string greeting thename, matching the return type.Final Answer:
function greet(name: string): string { return `Hello, ${name}`; } -> Option AQuick Check:
Correct parameter and return types = function greet(name: string): string { return `Hello, ${name}`; } [OK]
- Omitting parameter types in TypeScript
- Not returning a value when return type is declared
- Using console.log instead of return
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return `Hi, I am ${this.name}`;
}
}
const p = new Person('Anna');
console.log(p.greet());Solution
Step 1: Understand class construction
ThePersonclass setsthis.nameto the passed argument 'Anna' in the constructor.Step 2: Analyze the greet method output
Thegreetmethod returns a string includingthis.name, which is 'Anna'.Final Answer:
Hi, I am Anna -> Option AQuick Check:
Class property set correctly = 'Hi, I am Anna' [OK]
- Forgetting to assign constructor parameter to this.name
- Expecting undefined because of missing this
- Confusing method return with console.log output
class Car {
model: string;
constructor(model) {
this.model = model;
}
display() {
console.log('Model: ' + this.model);
}
}Solution
Step 1: Check constructor parameter types
In TypeScript, constructor parameters should have type annotations; here,modellacks a type.Step 2: Verify other parts
Thedisplaymethod does not require a return type annotation since it returns void implicitly.Final Answer:
Missing type annotation for constructor parameter 'model' -> Option DQuick Check:
Constructor parameters need types = Missing type annotation for constructor parameter 'model' [OK]
- Omitting parameter types in constructors
- Thinking methods must always declare return types
- Assuming properties must be private by default
Calculator with a method add that takes two numbers and returns their sum. Which code correctly implements this with proper types and usage?Solution
Step 1: Check method declaration and types
class Calculator { add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 3)); declaresaddwith parameters typed as numbers and return type number, which is correct.Step 2: Verify object creation and method call
class Calculator { add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 3)); creates an instance withnew Calculator()and callsadd(5, 3), which returns 8.Final Answer:
Correct class with typed method and proper usage -> Option BQuick Check:
Typed method + new instance + correct call = class Calculator { add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 3)); [OK]
- Calling class without 'new'
- Omitting parameter types
- Passing wrong argument types (like strings instead of numbers)
Ready to prove it?
Pass the test and this pattern moves unknown
