Skip to content

Commit 26bebb8

Browse files
committed
practice question 3 solved
1 parent fd0e172 commit 26bebb8

File tree

1 file changed

+37
-0
lines changed
  • src/module-4.5-practice

1 file changed

+37
-0
lines changed

src/module-4.5-practice/3.ts

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* You have an interface for Product, containing the product's id, name, price, and category.
3+
* You want to filter an array of Products based on a specific criterion and value.
4+
*
5+
* Write a TypeScript generic function that takes this array, a criterion , and returns a new
6+
* array containing only the products that match the given criterion and value. Use a generic
7+
* type parameter in the function signature to ensure type safety.
8+
*/
9+
10+
interface IProduct {
11+
id: number;
12+
name: string;
13+
price: number;
14+
category: string;
15+
}
16+
17+
const productArr: IProduct[] = [
18+
{ id: 1, name: "pen", price: 5, category: "study" },
19+
{ id: 2, name: "book", price: 500, category: "study" },
20+
{ id: 3, name: "pencil", price: 5, category: "study" },
21+
{ id: 4, name: "table", price: 5000, category: "furniture" },
22+
{ id: 5, name: "chair", price: 500, category: "furniture" },
23+
{ id: 6, name: "comic", price: 0, category: "entertainment" },
24+
{ id: 7, name: "anime", price: 0, category: "entertainment" },
25+
{ id: 8, name: "movie", price: 0, category: "entertainment" },
26+
];
27+
28+
const filterProduct = <T, U>(productArr: T, value: U) => {
29+
const newArr = (productArr as IProduct[]).filter(
30+
(product) => product.category === value
31+
);
32+
console.log(newArr);
33+
return newArr;
34+
};
35+
36+
filterProduct<IProduct[], string>(productArr, "study");
37+
// How can I make the property dynamic? like I can send id, name, price etc dynamically.

0 commit comments

Comments
 (0)