function sortArray<T extends [string, string, string][]>(array: T): T {
return array.sort((a, b) => a[0].localeCompare(b[0]));
}
function filterArray<T extends [string, string, string][]>(array: T, color: string): T {
return array.filter(item => item[1].toLowerCase() === color.toLowerCase()) as T;
}
function calculateFrequency<T extends [string, string, string][]>(array: T): {[key: string]: number} {
return array.reduce((acc, item) => {
acc[item[1]] = (acc[item[1]] || 0) + 1;
return acc;
}, {} as {[key: string]: number});
}
1. function calculateFrequency(array: T): {[key: string]: number} { ... }: This is a generic function declaration in TypeScript. The part is a type variable that stands for "any type". The extends [string, string, string][] part is a constraint on T, meaning T can be any type as long as it's an array of tuples, where each tuple has three string elements. The (array: T): {[key: string]: number} part means the function takes one argument array of type T and returns an object where the keys are strings and the values are numbers.
2. return array.reduce((acc, item) => { ... }, {} as {[key: string]: number});: This is the body of the function. It uses the reduce method of the array to reduce the array to a single output value. The reduce method takes a reducer function and an initial value as arguments. The initial value here is an empty object {} of type {[key: string]: number}.
3. (acc, item) => { ... }: This is the reducer function passed to the reduce method. It's an arrow function that takes two arguments acc and item and returns the accumulated value. acc is the accumulated value (the object being built), and item is the current element being processed in the array.
4. acc[item[1]] = (acc[item[1]] || 0) + 1;: This line of code is inside the reducer function. It increments the count of the color item[1] in the acc object. If the color doesn't exist in the acc object yet, acc[item[1]] will be undefined, so (acc[item[1]] || 0) + 1 will evaluate to 1. If the color already exists, it will increment the current count by 1.
5. return acc;: This line of code is also inside the reducer function. It returns the acc object for the next iteration or, if it's the last iteration, as the final result of the reduce method.