Skip to content

Commit

Permalink
Doubly Linked List (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
amitsuthar69 authored Dec 6, 2023
1 parent 611523d commit 6ac07c7
Show file tree
Hide file tree
Showing 5 changed files with 329 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
## Doubly Linked List

Unlike a singly linked list, where each node only has a pointer to the next node, A doubly linked list (DLL) has two pointers:

- Next pointer: Points to the next node in the list.
- Previous pointer: Points to the previous node in the list.

This additional Previous pointer allows traversing the list in both directions (forward and backward).

Advantages of DLL over singly linked list:

- Bidirectional traversal: Traversing the list in both directions is possible.
- Efficient deletion: Removing a node is faster as the previous node's pointer can be updated directly.
- Insertion before a node: Inserting a new node before a specific node is easier.

---

### DLL Node Creation

```cpp
class Node {
public:
int data;
Node* next;
Node* back;

Node(int val, Node* next1, Node* back1){
data = val;
next = next1;
back = back1;
}

Node(int val){
data = val;
next = nullptr;
back = nullptr;
}
};
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## Convert array to DLL

### Algorithm

1. Create a `head` node and assign it to arrays's first element.
2. Create a `prev` pointer to keep a track of just previous node. Initially, prev will point to head.
3. Start iteration form 1 to array size, during each iteration do these :
- Create a `temp` node and assign it the `i`th value of array. The `temp`'s next will point to `null` where as the `temp`'s back will point to `prev` node.
- For now the scenario is, the temp's back is connected to previous node, but still te prev node is disconnected to the temp node. So connect the prev node to temp node by pointing it to temp.
- Now as we've a brand new node, bring the prev node ahead (to the temp node.)
4. Return the `head` node in the end.

---

### Implementation

```cpp
Node* arr2DLL(vector<int> &arr){
Node* head = new Node(arr[0]);
Node* prev = head;
for (int i = 1; i < arr.size(); i++){
Node* temp = new Node(arr[i], nullptr, prev);
prev->next = temp;
prev = temp;
}
return head;
}
```
---
### Depiction
![arr2DLL](https://github.com/amitsuthar69/assets/blob/main/linked-lists/arr2Dll.png?raw=true)
181 changes: 181 additions & 0 deletions TypeScript/TypeScript-For-React/01-typed-props.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
## Typed Props in React

**Table of content :**

1. Inline Typed Props.
2. Type alias for Props.
3. Optional Props.
4. Union Literals in Prop Types.
5. CSSProprties Type.

In react, it's common that out functional component expects some external `props` in it. By default, those porps are typed `any` but then we loose the type safety of our props and that's something we don't want.

Hence it's necessary to correctly type props while extracting them into a component.

Below given is a typical javascript react app :

```tsx
export default function Home() {
const handleClick = () => {};
return (
<div>
<h2>Typed Props</h2>
<Button onClick={handleClick} fontSize={24} bgColor="#57863f" />
</div>
);
}

// warning : fontSize, onClick and bgColor are implicitly typed any
export default function Button({ fontSize, bgColor, onClick }) {
return (
<div>
<button onClick={onClick} classname={`bg-${bgColor}`}>
this is a Buttton
</button>
</div>
);
}
```

As we know that props are objects, we need to type each property in them. In the above example, **the component Button accepts destructured props which are implicitly typed to `any`**.

To type that prop object, we can use inline object type annotations.

```tsx
// no warning
export default function Button({
fontSize,
bgColor,
onClick,
}: {
foneSize: number;
bgColor: string;
onClick: () => void;
}) {
return (
<div>
<button onClick={onClick} classname={`bg-${bgColor}`}>
this is a Buttton
</button>
</div>
);
}
```

Well this annotation avoid the implicit `any` warning and our props are type safe now. But still it's so messed up and looks so repetitive and ugly!

---

### Type alias for Props

To clear this clutter, we can use object type alias to make our prop types look good.

```tsx
type ButtonProps = {
fontSize: number;
bgColor: string;
onClick: () => void;
};

export default function Button({ fontSize, bgColor, onClick }: ButtonProps) {
return (
<div>
<button classname={`bg-${bgColor}`}>this is a Buttton</button>
</div>
);
}
```

This component now looks good.

---

### Optional Props

If we're not sure about an incoming prop or if we missed some props to pass into our component, we can still type those unsured props using **Optional type members** syntax.

```ts
// Here the `isActive` prop is typed optionally.

type ButtonProps = {
fontSize: number;
bgColor: string;
isActive?: boolean;
};
```

---

### Return Type

By Default, `TSX` functional components has an implicit return type of `React.JSX.Element`. Hence we can avoid explicit typing of it as typescript infers it for us.

---

### Union Literals in Prop Types.

In our `ButtonProps`, we can also be more specific about the type of properties by using **Literal type unions**.

```ts
type ButtonProps = {
bgColor: "red" | "blue" | "green";
fontSize: number;
isActive?: boolean;
};
```

Now the `string` type of our `bgColor` is more specific and limited to `red` `blue` or `green`.

If multiple properties do share same union literals, then we can also extract them out. to makt it less repetetive

```ts
type Color = "red" | "blue" | "green";

type ButtonProps = {
bgColor: Color;
fontColor: Color;
fontSize: number;
isActive?: boolean;
};
```

---

### CSSProprties Types

For now, all our props are CSS poroperties and we could have 100 of them so we can't type them all individually. Here React help us with it's `React.CSSProperties` type.

Here's how we can use it :

```tsx
export default function Home() {
return (
<div>
<h2>Typed Props</h2>
<Button
style={{
backgroundColor: "red",
fontSize: 24,
padding: "1rem 2rem",
borderRadius: 8,
borderColor: "transparent",
}}
/>
</div>
);
}

type ButtonProps = {
style: React.CSSProperties;
};

export default function Button({ style }: ButtonProps) {
return (
<div>
<button style={style}>this is a Buttton</button>
</div>
);
}
```

The Style object in Button component can now have any number of props and we don't have to worry about styling them as `React.CSSProprties` handles everything.
58 changes: 58 additions & 0 deletions TypeScript/TypeScript-For-React/02-componentProps.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
## Component Props

In react, native tags has a lot of attributes and typing each of is not a good idea.

This below `Button` component has 3 button props for now (but it can be many) :

```tsx
const Home = () => {
const handleClick = () => {};
return (
<div>
<Button type="submit" onClick={handleClick} autoFocus={true} />
</div>
);
};

type ButtonProps = {
type: "submit" | "reset" | "button";
autoFocus?: boolean;
onClick: () => void;
};

const Button = ({ type, autoFocus, onClick }: ButtonProps) => {
return <button>Click me!</button>;
};
```

Instead of specifying types of individual properties, React helps us to deal this situation with a helper type, `React.ComponentProps<"...">` type. In the angle brackets, we can specify what tag it should be.

```tsx
type ButtonProps = React.ComponentProp<"button">;

const Button = ({ type, autoFocus, onClick }: ButtonProps) => return <button>Click me!</button>;
```

A hell lot of lines are taken away from our Button component as we have grouped the property types of a native button tag into a `React.ComponentProp<>` type.

We can also combine this ComponentProp with other custom prop types using **intersection (`&`)**:

```tsx
type ButtonProps = React.ComponentProp<"button"> & {
backgroundColor?: "red" | "blue";
}

const Button = ({ type, autoFocus, onClick, backgroundColor }: ButtonProps) => return <button>Click me!</button>;
```

---

We can make our code more cleaner yet using `...rest` operator (passing arbitary number of parameters) of TypeScript.

```tsx
type ButtonProps = React.ComponentProp<"button">;

const Button = ({ type, ...rest }: ButtonProps) => return <button type={type} {...rest} >Click me!</button>;
```

The `...rest` allows all the other props to be extracted here without specifically mentioning each of them. All the other properties are now stored into the rest **array**.
17 changes: 17 additions & 0 deletions TypeScript/TypeScript-For-React/03-typing-children.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
## Typing Children (React.ReactNode)

What is `ReactNode`?

`ReactNode` is a union type in React that represents any valid child element that can be passed to a component as a prop.

Using ReactNode for the children prop of your components has several benefits like Type safety, Readability, Performance, etc.

Using ReactNode :

```tsx
const MyComponent = (props: { children: React.ReactNode }) => {
return <div>{props.children}</div>;
};
```

...to be continued.

0 comments on commit 6ac07c7

Please sign in to comment.