Skip to content

Latest commit

 

History

History
359 lines (218 loc) · 9.54 KB

README.md

File metadata and controls

359 lines (218 loc) · 9.54 KB
  1. Array

  2. Objects

  3. List Of Objects

Note: Ensure you have typescript globally

npm install -g typescript

How to run?

Example:

tsc array.ts

node array.js


Arrays in TypeScript

An array is a data structure that stores a collection of elements (values), usually of the same type, in a single variable. Arrays allow you to store multiple values in an ordered list and provide easy access using an index.

In TypeScript, arrays can be declared to hold specific types, ensuring type safety. You can store a list of strings, numbers, or any other data types.

Defining an Array in TypeScript

Here's how you can define an array in TypeScript:

  1. Array of Numbers:

    let numbers: number[] = [1, 2, 3, 4, 5];
    
  2. Array of Strings:

    let shoppingList: string[] = ["milk", "bread", "eggs"];
    
  3. Array of Multiple Types (using any):

    let mixedArray: any[] = [1, "apple", true];
    
  4. Using Generics (Another way to define arrays):

    let fruits: Array<string> = ["apple", "banana", "orange"];
    

    EXAMPLE: SHOPPINGLIST

    let shoppingList: string[] = ["milk", "chocolate" , "shampoo"];
    
    console.log("List: " + shoppingList);
    

Basic Operations on Arrays (CRUD) in TypeScript

Create (Insert): Adding new items to an array can be done using the push() method:

shoppingList.push("Safeguard");

Accessing Array Elements

You can access elements in an array using their index. The index starts at 0.

plaintext let firstItem = shoppingList[0]; let secondItem = shoppingList[1];

Update: You can modify existing elements by directly accessing them via their index:

shoppingList[1] = "strawberry";

Delete: You can remove elements using splice():

shoppingList.splice(2, 1);  // Removes 1 item at index 2

This is how you use and manipulate arrays in TypeScript for basic operations like creating, reading, updating, and deleting elements.


OBJECT

An object in TypeScript is an instance that contains a set of key-value pairs. These pairs can hold various data types, including scalar values, functions, or even arrays of other objects. (GEEKSFORGEEKS)

SAMPLE OBJECT

shoppingObject.ts

export interface ShoppingObject{
id: number;
name: string;
price: number;
quantity: number;
}

SAMPLE OPERATION IN OBJECT

CREATE DATA IN OBJECT

main.ts

const shoppingObject: ShoppingObject = {
    id: 1,
    name: "test",
    price: 20,
    quantity: 2
};

console.log("List ");
console.log(shoppingObject);

ACCESS SPECIFIC VALUE

main.ts

//Access value
console.log("=====ACCESSSSING=====");
const name: string = shoppingObject.name;
console.log("FETCH_ name: " + name);

UDPATING SPECIFIC VALUE

main.ts

console.log("=====UPDATINGGG=====");

shoppingObject.name = "thirdy";
console.log("UPDATED_ now the object: " );
console.log(shoppingObject);


Array of Objects

Defining interfaces or type, we will provide the property names and their types inside them and assign them as a explicit type the array. (https://www.geeksforgeeks.org/how-can-i-define-an-array-of-objects-in-typescript/#using-the-inbuilt-interfaces-and-type)

sample Array of Object

ShoppingListObj.ts

export interface ShoppingListObj{
  id: number,
  name: string,
  price: number,
  quantity: number
}

1. Create Operation

This function adds a new product to the products array.

main.ts

const shoppingList: ShoppingListObj[] = [];

shoppingList.push({id: 1, name: "test", price: 100, quantity: 5});
shoppingList.push({id: 2, name: "second", price: 100, quantity: 5});

console.log("List ");
console.log(shoppingList);

Explanation:

  • Parameter: It accepts a parameter shoppingList of type ShoppingListObj. This represents the new list you want to add.

  • Operation: The shopping or cart is added to the shoppingList array using the push() method.


2. Read Product

This function fetches a shoppingList by its id.

 const readMyCart = (id: number): ShoppingListObj | undefined => {
       return shoppingList.find(p => p.id === id);
 };

Explanation:

  • Parameter: The function accepts productId which is the ID of the product to search for.

  • Operation: It uses find() to search through the products array for the product with the matching id.

  • Conditional Logging:

    • If the product is found, it logs "Product found" and returns the product.

    • If not found, it logs "Product not found" and returns undefined.

Example of usage:

readProduct(1);  // Tries to find the product with id = 1

This will search for the product with ID 1. If it exists, the product will be logged and returned.


3. updateProduct (Update Operation)

This function updates the fields of a product using its id.

const updateMyCart = (id: number, updatedData: Partial<ShoppingListObj>) => {
        const findIndex = shoppingList.findIndex(p => p.id === id);
        if (findIndex > -1) {
            shoppingList[findIndex] = { ...shoppingList[findIndex],  ...updatedData };
            console.log("UPDATED DATA: ");
            console.log(updatedData);
            console.log("UPDATED LIST: ");
            console.log(shoppingList);
        } else {
            console.log("Product Not Found");
        }
   };

Explanation:

  • Parameters:

    • id: The ID of the product to be updated.

    • updatedData: A Partial<ShoppingListObj>, meaning it allows you to pass only the fields you want to update, without needing to provide the whole product.

  • Operation:

    • The function uses findIndex() to locate the product in the products array by its id.

    • If the product is found, it updates the fields by using object spread (...) to merge the existing product data with the new updatedData.

Example of usage:

updateMyCart(2, {name: "shampoo"});

This will update the product with ID 2 by setting its name to shampoo

OUTPUT:


4.Delete Operation

This function deletes a product by its id.

 const deleteItem = (id: number) => {
        const findIndex = shoppingList.findIndex(p => p.id = id);
        if (findIndex !== -1){
            const deleteItem = shoppingList.splice(id, 1);
            console.log("Deleted Item: " + deleteItem[0]);
            console.log("UPDATED LIST: ");
            console.log(shoppingList);
        }
 }

Explanation:

  • Parameter: It accepts productId, the ID of the product to be deleted.

  • Operation:

    • It uses findIndex() to locate the product in the products array.

    • If the product is found, it is removed using splice() (which removes the product at the found index).

    • The deleted product is then logged.

    Example of usage:

deleteItem(1);  // Deletes the product with id = 1

This will remove the product with ID 1 from the shoppingList array if it exists.

OUTPUT


AGAIN

  • Create: Adds a new product to the list.

  • Read: Retrieves a product by its ID.

  • Update: Modifies specific fields of a product.

  • Delete: Removes a product by its ID.

Each function uses basic array methods (push, find, findIndex, splice) to manipulate the products array and logs the results for clarity.

GITHUB REPOSITORY:

https://github.com/thirdygayares/typescripts-data-structure.git