T040 Mastering Methods and Functions
In this assignment, you’ll delve into the world of TypeScript methods and functions. You’ll practice creating and invoking functions, working with lambda expressions, and exploring advanced function concepts.
Setup
- Create a new TypeScript file
Basic Methods
- Simple Function: Create a function named
greetthat takes anameparameter of typestringand returns a greeting message. Invoke the function and print the result. - Function with Multiple Parameters: Create a function named
addthat takes two parameters of typenumberand returns their sum. Invoke the function with different arguments and print the results.
Lambda Expressions
- Simple Lambda: Create a lambda function named
squarethat takes a number and returns its square. Invoke the function and print the result. - Lambda with Multiple Statements: Create a lambda function named
describethat takes anameandageparameter and returns a string describing the person. The function should have multiple statements. Invoke the function and print the result.
Advanced Function Concepts
- Function as a Parameter: Create a function named
operatethat takes two numbers and a function as parameters. This function should apply the provided function to the two numbers and return the result. Test this with simple functions like addition and multiplication. - Function Returning a Function: Create a function named
getFunctionthat generates a random number (1 or 2). If the number is 1, it should return a function that calculates the square of a number. If the number is 2, it should return a function that calculates the cube of a number. InvokegetFunctionand then invoke the returned function, printing the result.
Challenge: Dynamic Function Invocation
- Dynamic Function Selector: Based on the previous task, after getting the function from
getFunction, invoke it with a range of numbers from 1 to 5 using a loop, printing the results.
Solution
Solution
Basic Methods
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice"));
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 3));
Lambda Expressions
let square = (x: number) => x * x;
console.log(square(4));
let describe = (name: string, age: number) => {
return `${name} is ${age} years old.`;
}
console.log(describe("Bob", 25));
Advanced Function Concepts
function operate(x: number, y: number, operation: (a: number, b: number) => number): number {
return operation(x, y);
}
console.log(operate(4, 5, (a, b) => a + b));
console.log(operate(4, 5, (a, b) => a * b));
function getFunction(): (x: number) => number {
let randomNumber = Math.floor(Math.random() * 2) + 1;
if (randomNumber === 1) {
return x => x * x; // square
} else {
return x => x * x * x; // cube
}
}
let randomFunction = getFunction();
console.log(randomFunction(3));