Complete the code to declare a generic function that returns the first element of an array.
function firstElement<[1]>(arr: [1][]): [1] { return arr[0]; }
The generic type parameter T is commonly used to represent any type. Here, it allows the function to accept an array of any type and return an element of that same type.
Complete the code to create a generic function that returns the length of any array.
function getLength<[1]>(items: [1][]): number { return items.length; }
The generic type parameter T is used here to represent the type of elements in the array. The function returns the length of the array regardless of element type.
Fix the error in the generic function that swaps the first and last elements of an array.
function swapFirstLast<[1]>(arr: [1][]): [1][] { const temp = arr[0]; arr[0] = arr[arr.length - 1]; arr[arr.length - 1] = temp; return arr; }
The generic type parameter T is used consistently to indicate the type of elements in the array. This ensures the function works for any array type.
Fill both blanks to create a generic function that filters an array based on a condition.
function filterArray<[1]>(arr: [1][], predicate: (item: [2]) => boolean): [1][] { return arr.filter(predicate); }
The generic type parameter T is used for both the array element type and the predicate function parameter to ensure type consistency.
Fill all three blanks to create a generic function that maps an array to another array using a transform function.
function mapArray<[1] , [2]>(arr: [1][], transform: (item: [3]) => [2]): [2][] { return arr.map(transform); }
The generic type parameters T and U represent the input and output types respectively. The function uses these to type the array and transform function correctly.