TypeScript generic swap function example
TypeScript Advance Types: Exercise-10 with Solution
Write a TypeScript generic function that accepts two arguments: an array of any type and two indices. The function should swap the elements at the specified indices and return the modified array.
Sample Solution:
TypeScript Code:
// Generic function 'swap' that accepts an array and two indices
function swap(arr: T[], index1: number, index2: number): T[] {
// Check if the indices are within the valid range
if (index1 < 0 || index1 >= arr.length || index2 < 0 || index2 >= arr.length) {
throw new Error("Invalid indices");
}
// Perform the swap using a temporary variable
const temp: T = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
return arr;
}
// Test the 'swap' function with an array of numbers
const nums: numbers[] = [21, 45, 76, 87, 14];
console.log("Original Array:", nums);
swap(nums, 1, 3); // Swap elements at indices 1 and 3
console.log("Modified Array:", nums);
Explanations:
In the exercise above -
- First, we define a generic function "swap()" that accepts three parameters: an array arr of type T[] (an array of any type), and two indices 'index1' and 'index2'.
- Inside the function, we first check if the indices are within the valid range (between 0 and arr.length - 1). If the indices are invalid, we throw an error.
- We then perform the swap operation using a temporary variable 'temp'.
- Finally, we return the modified array 'arr' after the swap operation.
Output:
"Original Array:" [21, 45, 76, 87, 14] "Modified Array:" [21, 87, 76, 45, 14]
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript generic function example.
Next: TypeScript Mapped Type: Making properties optional.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/typescript-exercises/typescript-advance-types-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics