diff --git a/practice1.ts b/practice1.ts index 85eaf5e..8393eba 100644 --- a/practice1.ts +++ b/practice1.ts @@ -16,16 +16,26 @@ Your goal is to write functions that interact with this data. * 2. name of type string * 3. category of type string * 4. price of type number - * + * * *************/ - +interface Product { + id: number; + name: string; + category: string; + price: number; +} // ✅ Sample data to test your functions const products: Product[] = [ - { id: 201, name: "Laptop", category: "Electronics", price: 999.99 }, - { id: 202, name: "T-shirt", category: "Clothing", price: 19.99 }, - { id: 203, name: "Coffee Maker", category: "Kitchen Appliances", price: 79.99 }, - { id: 204, name: "Running Shoes", category: "Footwear", price: 59.99 }, - { id: 205, name: "Bookshelf", category: "Furniture", price: 149.99 }, + { id: 201, name: "Laptop", category: "Electronics", price: 999.99 }, + { id: 202, name: "T-shirt", category: "Clothing", price: 19.99 }, + { + id: 203, + name: "Coffee Maker", + category: "Kitchen Appliances", + price: 79.99, + }, + { id: 204, name: "Running Shoes", category: "Footwear", price: 59.99 }, + { id: 205, name: "Bookshelf", category: "Furniture", price: 149.99 }, ]; /************************************************************** @@ -34,8 +44,16 @@ Create a function `getProductName` that: - Accepts a `product` of type `Product` - Returns the name of the product **************************************************************/ - -// console.log(getProductName(products[0])); // "Laptop" +function getProductName(product: Product): boolean { + if (product.name === "Laptop") { + return true; + } else { + return false; + } +} +const newProducts = products.filter(getProductName); +const productName = newProducts.map((item) => item.name); +console.log(productName); // "Laptop" /************************************************************** ✅ Question 2: @@ -43,18 +61,35 @@ Create a function `isProductCategoryMatching` that: - Accepts a `product` of type `Product` and a `category` (string) - Returns `true` if the product’s category matches the given category **************************************************************/ - -// console.log(isProductCategoryMatching(products[1], "Clothing")); // true +function isProductCategoryMatching( + product: Product, + category: string +): boolean { + if (product.category === "Clothing") { + return true; + } else { + return false; + } +} +console.log(isProductCategoryMatching(products[1], "Clothing")); // true /************************************************************** ✅ Question 3: Create a function `addProduct` that: - Accepts an array of `Product` and a new `Product` -- Adds the product to the array and returns the updated array -**************************************************************/ - -// const newProduct: Product = { id: 206, name: "Headphones", category: "Electronics", price: 149.99 }; -// console.log(addProduct(products, newProduct)); +// - Adds the product to the array and returns the updated array +// **************************************************************/ +function addProduct(products: Product[], newProduct: Product): Product[] { + return [...products, newProduct]; +} +const newProduct: Product = { + id: 206, + name: "Headphones", + category: "Electronics", + price: 149.99, +}; +const updatedProducts = addProduct(products, newProduct); +console.log(updatedProducts); /************************************************************** ✅ Question 4: @@ -62,8 +97,16 @@ Create a function `countElectronicsProducts` that: - Accepts an array of products - Returns the number of products in the "Electronics" category **************************************************************/ - -// console.log(countElectronicsProducts(products)); +function countElectronicsProducts(prodects1: Product): boolean { + if (prodects1.category === "Electronics") { + return true; + } else { + return false; + } +} +const prodectsrFilter = products.filter(countElectronicsProducts); +prodectsrFilter.length; +console.log(prodectsrFilter.length); /************************************************************** ✅ Question 5: 🌶️ @@ -71,8 +114,19 @@ Create a function `listProductNamesByCategory` that: - Accepts an array of products and a category - Returns an array of product names that match the category **************************************************************/ - -// console.log(listProductNamesByCategory(products, "Electronics")); +function listProductNamesByCategory( + products: Product[], + category: string +): string[] { + const filteredProducts = products.filter( + (product) => product.category === category + ); + const newProducts = filteredProducts.map((item) => item.name); + return newProducts; + // products.filter((product) => product.category === category).map((item) => item.name) +} + +console.log(listProductNamesByCategory(products, "Electronics")); /************************************************************** ✅ Question 6: 🌶️🌶️ @@ -80,8 +134,12 @@ Create a function `getCheapestProduct` that: - Accepts an array of products - Returns the product object with the lowest price **************************************************************/ - -// console.log(getCheapestProduct(products)); +function getCheapestProduct(products: Product[]): string[] { + return products + .filter((item) => item.price === 19.99) + .map((item) => item.name); +} +console.log(getCheapestProduct(products)); /************************************************************** ✅ Question 7: @@ -90,8 +148,10 @@ Create a function `removeProductById` that: - Removes the product with that ID - Returns the updated array **************************************************************/ - -// console.log(removeProductById(products, 202)); +function removeProductById(products: Product[], productID: number): Product[] { + return products.filter((item) => item.id !== productID); +} +console.log(removeProductById(products, 202)); /************************************************************** ✅ Question 8: 🌶️🌶️🌶️ @@ -99,5 +159,14 @@ Create a function `getProductsByPriceRange` that: - Accepts an array of products, a min price, and a max price - Returns an array of products within that price range (inclusive) **************************************************************/ - -// console.log(getProductsByPriceRange(products, 19.99, 59.99)); \ No newline at end of file +function getProductsByPriceRange( + products: Product[], + minPrice: number, + maxPrice: number +): string[] { + const productsPrice = products + .filter((item) => item.price >= minPrice && item.price <= maxPrice) + .map((item) => item.name); + return productsPrice; +} +console.log(getProductsByPriceRange(products, 19.99, 59.99)); diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index 904d43f..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "libReplacement": true, /* Enable lib replacement. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ - // "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } -}