├── .gitignore
├── .vscode
├── extensions.json
└── launch.json
├── LICENSE
├── README.md
├── SECURITY.md
├── astro.config.mjs
├── package-lock.json
├── package.json
├── public
└── favicon.svg
├── src
├── assets
│ └── houston.webp
├── content
│ ├── config.ts
│ └── docs
│ │ ├── devops
│ │ └── aws_node_deployment.md
│ │ ├── dsa-js
│ │ ├── linkedlist.md
│ │ ├── medium.md
│ │ └── questions.md
│ │ ├── index.mdx
│ │ ├── intro
│ │ └── intro.md
│ │ ├── javaScript
│ │ ├── javascript_datatypes.md
│ │ ├── javascript_introduction.md
│ │ ├── javascript_rest_and_spread_operator.md
│ │ ├── javascript_stack_and_heap_memory.md
│ │ ├── javascript_variables.md
│ │ └── jsvar.md
│ │ ├── main
│ │ ├── aws
│ │ │ └── ec2
│ │ │ │ ├── 1.png
│ │ │ │ ├── 10.png
│ │ │ │ ├── 11.png
│ │ │ │ ├── 12.png
│ │ │ │ ├── 13.png
│ │ │ │ ├── 14.png
│ │ │ │ ├── 15.png
│ │ │ │ ├── 16.png
│ │ │ │ ├── 17.png
│ │ │ │ ├── 2.png
│ │ │ │ ├── 21.png
│ │ │ │ ├── 22.png
│ │ │ │ ├── 23.png
│ │ │ │ ├── 24.png
│ │ │ │ ├── 25.png
│ │ │ │ ├── 26.png
│ │ │ │ ├── 27.png
│ │ │ │ ├── 28.png
│ │ │ │ ├── 29.png
│ │ │ │ ├── 3.png
│ │ │ │ ├── 30.png
│ │ │ │ ├── 4.png
│ │ │ │ ├── 5.png
│ │ │ │ ├── 6.png
│ │ │ │ ├── 7.png
│ │ │ │ ├── 8.png
│ │ │ │ └── 9.png
│ │ ├── dsa-js
│ │ │ └── dsa-js-calculate-form-natural-number.png
│ │ ├── python
│ │ │ ├── python1.jpeg
│ │ │ └── python_inner_working2.png
│ │ └── typescript
│ │ │ └── typescript-inner-working-guide-and-grow.png
│ │ ├── node
│ │ └── node.md
│ │ ├── python
│ │ ├── data-types-python.md
│ │ ├── innerworking.md
│ │ ├── introduction.md
│ │ ├── mutable-and-immutable.md
│ │ ├── numbers-in-python.md
│ │ └── operators-in-python.md
│ │ ├── tipsandtools
│ │ ├── httpresponsestatuscode.md
│ │ └── regularexpressions.md
│ │ └── typeScript
│ │ ├── innerworking.md
│ │ ├── typescript-classes.md
│ │ ├── typescript-data-types.md
│ │ ├── typescript-decorators.md
│ │ ├── typescript-functions.md
│ │ ├── typescript-generics.md
│ │ ├── typescript-index-signatures.md
│ │ ├── typescript-literal-types.md
│ │ ├── typescript-modules.md
│ │ ├── typescript-namespaces.md
│ │ ├── typescript-optional-properties.md
│ │ ├── typescript-type-and-interfaces.md
│ │ ├── typescript-type-assertions.md
│ │ ├── typescript-type-guards.md
│ │ ├── typescript-utility-types.md
│ │ └── typescript.md
└── env.d.ts
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | # build output
2 | dist/
3 | # generated types
4 | .astro/
5 |
6 | # dependencies
7 | node_modules/
8 |
9 | # logs
10 | npm-debug.log*
11 | yarn-debug.log*
12 | yarn-error.log*
13 | pnpm-debug.log*
14 |
15 |
16 | # environment variables
17 | .env
18 | .env.production
19 |
20 | # macOS-specific files
21 | .DS_Store
22 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": ["astro-build.astro-vscode"],
3 | "unwantedRecommendations": []
4 | }
5 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "command": "./node_modules/.bin/astro dev",
6 | "name": "Development server",
7 | "request": "launch",
8 | "type": "node-terminal"
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Guide And Grow
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Guide Docs
2 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Use this section to tell people about which versions of your project are
6 | currently being supported with security updates.
7 |
8 | | Version | Supported |
9 | | ------- | ------------------ |
10 | | 5.1.x | :white_check_mark: |
11 | | 5.0.x | :x: |
12 | | 4.0.x | :white_check_mark: |
13 | | < 4.0 | :x: |
14 |
15 | ## Reporting a Vulnerability
16 |
17 | Use this section to tell people how to report a vulnerability.
18 |
19 | Tell them where to go, how often they can expect to get an update on a
20 | reported vulnerability, what to expect if the vulnerability is accepted or
21 | declined, etc.
22 |
--------------------------------------------------------------------------------
/astro.config.mjs:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "astro/config";
2 | import starlight from "@astrojs/starlight";
3 |
4 | // https://astro.build/config
5 | export default defineConfig({
6 | integrations: [
7 | starlight({
8 | title: "Guide Docs",
9 | social: {
10 | github: "https://github.com/saurabhjaykar1603",
11 | },
12 | sidebar: [
13 | {
14 | label: "Introduction",
15 | items: [
16 | { label: "Introduction to Guide Docs", link: "/intro/intro/" },
17 | ],
18 | },
19 | // {
20 | // label: "HTML",
21 | // items: [
22 | // // Each item here is one entry in the navigation menu.
23 | // { label: "What is HTML", link: "/html/html/" },
24 | // ],
25 | // },
26 | {
27 | label: "Python",
28 | items: [
29 | { label: "Introduction to Python", link: "/python/introduction" },
30 | { label: "Python inner working", link: "/python/innerworking" },
31 | {
32 | label: "Mutable and Immutable Types in Python",
33 | link: "/python/mutable-and-immutable",
34 | },
35 | {
36 | label: "Data Types in Python",
37 | link: "/python/data-types-python",
38 | },
39 | {
40 | label: "Numbers in Python",
41 | link: "/python/numbers-in-python"
42 | },
43 | {
44 | label: "Operators in Python",
45 | link: "/python/operators-in-python",
46 | },
47 | ],
48 | },
49 | {
50 | label: "TypeScript",
51 | items: [
52 | { label: "What is TypeScript", link: "/typescript/typescript/" },
53 | {
54 | label: "Typescript Inner Working and Installation",
55 | link: "/typescript/innerworking",
56 | },
57 | {
58 | label: "TypeScript Data Types",
59 | link: "/typescript/typescript-data-types",
60 | },
61 | {
62 | label: "Types and Interfaces in TypeScript",
63 | link: "/typescript/typescript-type-and-interfaces",
64 | },
65 | {
66 | label: "TypeScript Optional Properties",
67 | link: "/typescript/typescript-optional-properties",
68 | },
69 | {
70 | label: "TypeScript Type Assertions",
71 | link: "/typescript/typescript-type-assertions",
72 | },
73 | {
74 | label: "Functions in TypeScript",
75 | link: "/typescript/typescript-functions",
76 | },
77 | {
78 | label: "Classes in TypeScript",
79 | link: "/typescript/typescript-classes",
80 | },
81 | {
82 | label: "Generics in TypeScript",
83 | link: "/typescript/typescript-generics",
84 | },
85 | {
86 | label: "Literal Types in TypeScript",
87 | link: "/typescript/typescript-literal-types",
88 | },
89 | {
90 | label: "Namespaces in TypeScript",
91 | link: "/typescript/typescript-namespaces",
92 | },
93 | {
94 | label: "Type Guards in TypeScript",
95 | link: "/typescript/typescript-type-guards",
96 | },
97 | {
98 | label: "Index Signatures in TypeScript",
99 | link: "/typescript/typescript-index-signatures",
100 | },
101 | {
102 | label: "Utility Types in TypeScript",
103 | link: "/typescript/typescript-utility-types",
104 | },
105 | {
106 | label: "Modules in TypeScript",
107 | link: "/typescript/typescript-modules",
108 | },
109 | {
110 | label: "Decorators in TypeScript",
111 | link: "/typescript/typescript-decorators",
112 | },
113 | ],
114 | },
115 |
116 | {
117 | label: "JavaScript",
118 | items: [
119 | {
120 | label: "What is JavaScript",
121 | link: "/javascript/javascript_introduction",
122 | },
123 | {
124 | label: "Variables in JavaScript",
125 | link: "/javascript/javascript_variables",
126 | },
127 | {
128 | label: "Datatypes in JavaScript",
129 | link: "/javascript/javascript_datatypes",
130 | },
131 | {
132 | label: "Stack and Heap Memory in JavaScript",
133 | link: "/javascript/javascript_stack_and_heap_memory",
134 | },
135 | {
136 | label: "Rest and Spread Operator in JavaScript",
137 | link: "/javascript/javascript_rest_and_spread_operator",
138 | },
139 | ],
140 | },
141 | {
142 | label: "Node",
143 | items: [{ label: "What is Node", link: "/node/node/" }],
144 | },
145 | {
146 | label: "Dsa JavaScript Questions",
147 | items: [
148 | { label: "Easy", link: "/dsa-js/questions/" },
149 | { label: "Medium", link: "/dsa-js/medium/" },
150 | { label: "Advance Linked List", link: "/dsa-js/linkedlist/" },
151 | ],
152 | },
153 | {
154 | label: "Devops",
155 | items: [
156 | {
157 | label: "Full Node.js Deployment to AWS",
158 | link: "/devops/aws_node_deployment",
159 | },
160 | ],
161 | },
162 |
163 | {
164 | label: "Tips and Tools",
165 | items: [
166 | {
167 | label: "Regular Expressions in Javascript",
168 | link: "/tipsandtools/regularexpressions/",
169 | },
170 | {
171 | label: "HTTP Response Status Codes",
172 | link: "/tipsandtools/httpresponsestatuscode/",
173 | },
174 | ],
175 | },
176 | ],
177 | }),
178 | ],
179 | });
180 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "guide.docs",
3 | "type": "module",
4 | "version": "0.0.1",
5 | "scripts": {
6 | "dev": "astro dev",
7 | "start": "astro dev",
8 | "build": "astro build",
9 | "preview": "astro preview",
10 | "astro": "astro"
11 | },
12 | "dependencies": {
13 | "@astrojs/starlight": "^0.23.2",
14 | "astro": "^4.8.6",
15 | "sharp": "^0.32.6"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/public/favicon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/assets/houston.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/assets/houston.webp
--------------------------------------------------------------------------------
/src/content/config.ts:
--------------------------------------------------------------------------------
1 | import { defineCollection } from 'astro:content';
2 | import { docsSchema } from '@astrojs/starlight/schema';
3 |
4 | export const collections = {
5 | docs: defineCollection({ schema: docsSchema() }),
6 | };
7 |
--------------------------------------------------------------------------------
/src/content/docs/devops/aws_node_deployment.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Full Node.js Deployment to AWS
3 | description: A beginner-friendly Guide for Node.js Deployment to AWS
4 | ---
5 |
6 | ## FREE SSL, NGINX | Node js HTTPS Server
7 |
8 | ---
9 |
10 | **In this tutorial, we will walk through the complete process of deploying a Node.js application on an `AWS EC2 `instance using `PM2 for process management`. Additionally, we will configure an NGINX reverse proxy for routing requests to the application and secure the deployment with a free SSL certificate from Let's Encrypt. This guide ensures a production-ready setups , along with HTTPS support for secure communication.**
11 |
12 | ---
13 |
14 | ### Step 1: Create an AWS Account
15 |
16 | - First, you need to create an AWS account. Go to the AWS website and sign up for a free account. You will need to provide some basic information about yourself and your company.
17 |
18 | 
19 |
20 | ---
21 |
22 | ### Step 2: Create an EC2 Instance
23 |
24 | - An EC2 (Elastic Compute Cloud) instance is a virtual server in Amazon’s cloud where you can run your applications. Follow these steps to create an EC2 instance:
25 |
26 | 1. **Navigate to the EC2 Dashboard**:
27 |
28 | - Once logged into your AWS account, go to the EC2 service by searching "EC2" in the AWS Management Console.
29 |
30 | 
31 |
32 | 2. **Launch a New EC2 Instance**:
33 |
34 | - Click the **"Launch Instance"** button.
35 | 
36 | - Choose the **Amazon Machine Image (AMI)**. For Node.js deployments, select a Linux-based AMI, such as **Ubuntu Server 24.04 LTS**.
37 | 
38 |
39 | 3. **Select an Instance Type**:
40 |
41 | - For development or small-scale production, the **t2.micro** instance (eligible for the AWS Free Tier) is recommended.
42 | - This instance provides 1 vCPU and 1GB of memory.
43 | 
44 |
45 | 4. **Create a Key Pair**:
46 |
47 | - If you don’t already have a key pair, click **Create new key pair**.
48 | 
49 |
50 | - Select **RSA** as the key type and **.pem** as the format. This key pair will be used to securely connect to your instance.
51 | - Download the `.pem` file and store it in a safe location. You’ll need this to access the instance using SSH.
52 | 
53 |
54 | - If you already have an existing key pair, you can select it from the dropdown.
55 |
56 | 5. **Configure Instance Details**:
57 |
58 | - Choose the default settings unless you have specific network preferences. Ensure you place your instance in the right VPC and subnet.
59 | 
60 |
61 | 6. **Add Storage**:
62 |
63 | - The default storage size is typically sufficient for most Node.js applications, but you can adjust it if your project requires additional space. For standard Node.js deployments, 8GB to 16GB of storage is generally recommended to ensure smooth operation and accommodate application files, logs, and other data.
64 |
65 | - Your Instance is Ready 🎉.
66 | 
67 |
68 | ---
69 |
70 | ### Step 3 : Assign an Elastic IP
71 |
72 | - An Elastic IP (EIP) is a static IP address that you can use to connect to
73 | your instance from anywhere in the world. Follow these steps to assign an EIP
74 |
75 | 1. **Assign an Elastic IP**:
76 |
77 | - After launching the instance, navigate to the **Elastic IPs** section in the EC2 Dashboard.
78 | 
79 | - Click **Allocate Elastic IP address** to reserve a static public IP.
80 | 
81 | 
82 | 
83 | - Once allocated, select the Elastic IP, click **Actions**, and choose **Associate Elastic IP**.
84 | - In the association options, select your EC2 instance. This ensures that your instance retains the same public IP address, even after a reboot, making it easier to connect and manage.
85 | 
86 |
87 | ---
88 |
89 | ### Step 4 : Configure Security Groups
90 |
91 | 1. **Navigate to Security groups**:
92 |
93 | - In the EC2 dashboard, navigate to the **Instances** section.
94 | - Click on the **Security** tab.
95 | - Click on the **Security Groups** tab.
96 | 
97 | - Click on the **Edit Inbound Rules** tab.
98 | 
99 |
100 | 2. **Configure Security Groups**:
101 |
102 | Security groups act as a virtual firewall. Add the following inbound rules:
103 |
104 | - **SSH (Port 22)**: Allows you to connect to the instance using SSH.
105 | - **HTTP (Port 80)**: Required for regular web traffic.
106 | - **HTTPS (Port 443)**: For secure web traffic after SSL is configured.
107 | - Optionally, add **Custom TCP rules** for any other required ports.
108 |
109 | - For example:
110 | - **Backend API**: If your server is listening on ports like **8000** or **5000**, add those ports to allow access.
111 | - **Frontend (React)**: If you're running a React app on port **3000**, add a rule for port **3000** to access the frontend.
112 | 
113 | - save 🎉
114 |
115 | ---
116 |
117 | ### Step 5 : Connect to Your Instance
118 |
119 | - **Connect to your instance using SSH:**
120 |
121 | - After assigning an Elastic IP address to your instance, connect to it via SSH by following these steps:
122 |
123 | 
124 |
125 | ```bash
126 | ssh -i "path-to-your-key.pem" ubuntu@your-instance-public-ip
127 | ```
128 |
129 | - Replace `"path-to-your-key.pem"` with the path to your private key file.
130 | - Replace `"your-instance-public-ip"` with the public IP address of your instance.
131 | - You should now be logged in to your instance.
132 | 
133 |
134 | ---
135 |
136 | ### Step 6 : Install Node.js on Virtual Machine
137 |
138 | - **Install Node.js**:
139 |
140 | To install Node.js on your instance, run the following commands:
141 |
142 | ```bash
143 | curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
144 | sudo apt install -y nodejs
145 | node --version
146 | ```
147 |
148 | - This will install Node.js version 18.x.
149 | - Verify the installation by checking the Node.js version with the `node --version` command.
150 | 
151 |
152 | ---
153 |
154 | ### Step 7 : Clone Your Project ans install Dependencies
155 |
156 | - **Clone your project**:
157 |
158 | To clone your project from a Git repository, use the following command:
159 |
160 | ```bash
161 | git clone https://github.com/your-username/your-repository.git
162 | ```
163 |
164 | - Replace `your-username` with your GitHub username (or relevant Git hosting service).
165 | - Replace `your-repository` with the name of your repository.
166 |
167 | Once the project is cloned, navigate into the project directory:
168 |
169 | ```bash
170 | cd your-repository
171 | ```
172 |
173 | - Replace `your-repository` with the name of your cloned repository.
174 |
175 | ---
176 |
177 | - **Install project dependencies**:
178 |
179 | After cloning the repository, run the following command to install the necessary dependencies:
180 |
181 | ```bash
182 | npm install
183 | ```
184 |
185 | This will install all the required Node.js modules listed in your `package.json` file.
186 | 
187 |
188 | ---
189 |
190 | ### Step 8 : Install PM2 Globally and Test Your App
191 |
192 | - **PM2 is a process manager for Node.js applications that helps you keep your apps running continuously, even after a server restart. It allows you to manage, monitor, and scale applications easily with commands for starting, stopping, restarting, and viewing logs. PM2 also provides features like automatic startup on boot, log management, and process clustering for better performance.**
193 | - **Install PM2 globally**:
194 |
195 | Use the following command to install PM2 globally on your server:
196 |
197 | ```bash
198 | sudo npm install pm2@latest -g
199 | ```
200 |
201 | PM2 is a process manager that helps you manage and keep your Node.js application running in the background.
202 |
203 | ---
204 |
205 | - **Start your Node.js application using PM2**:
206 |
207 | 1. Navigate to the directory where your Node.js app is located:
208 |
209 | ```bash
210 | cd /path/to/your/app
211 | ```
212 |
213 | 2. Start your application with PM2:
214 |
215 | ```bash
216 | pm2 start server.js -- name my-node-app
217 | ```
218 |
219 | 
220 |
221 | Replace `server.js ` with the entry point file of your Node.js application.
222 |
223 | ---
224 |
225 | - **Check the status of your application**:
226 |
227 | To view the status of your app, run:
228 |
229 | ```bash
230 | pm2 list
231 | ```
232 |
233 | This will display all running applications managed by PM2.
234 |
235 | ---
236 |
237 | - **Set PM2 to start on boot**:
238 |
239 | To ensure that PM2 and your app start automatically when the server restarts, run the following command:
240 |
241 | ```bash
242 | pm2 startup
243 | ```
244 |
245 | Then, follow the instructions printed on your terminal to enable PM2 at startup.
246 |
247 | ---
248 |
249 | - **Save the current PM2 process list**:
250 |
251 | After starting your application, save the PM2 process list to restore it on reboot:
252 |
253 | ```bash
254 | pm2 save
255 | ```
256 |
257 | ---
258 |
259 | - **View application logs**:
260 |
261 | To monitor the logs of your Node.js app, use the following command:
262 |
263 | ```bash
264 | pm2 logs
265 | ```
266 |
267 | 
268 |
269 | This will allow you to track logs for debugging or monitoring purposes.
270 |
271 | - **Other PM2 Commands**
272 |
273 | - **Show details of an app**:
274 |
275 | To view detailed information about a specific application, use:
276 |
277 | ```bash
278 | pm2 show app
279 | ```
280 |
281 | Replace `app` with the name or ID of your application.
282 |
283 | ---
284 |
285 | - **Check the status of all applications**:
286 |
287 | To see the status of all running applications:
288 |
289 | ```bash
290 | pm2 status
291 | ```
292 |
293 | ---
294 |
295 | - **Restart an application**:
296 |
297 | To restart a specific app:
298 |
299 | ```bash
300 | pm2 restart app
301 | ```
302 |
303 | Replace `app` with the name or ID of your application.
304 |
305 | ---
306 |
307 | - **Stop an application**:
308 |
309 | To stop a running application:
310 |
311 | ```bash
312 | pm2 stop app
313 | ```
314 |
315 | Replace `app` with the name or ID of your application.
316 |
317 | ---
318 |
319 | - **Clear logs**:
320 |
321 | To clear all logs maintained by PM2:
322 |
323 | ```bash
324 | pm2 flush
325 | ```
326 |
327 | ---
328 |
329 | **Note:** The above commands are for the basic usage of PM2. For more advanced features
330 | and options, you can refer to the official PM2 documentation.
331 |
332 | ---
333 |
334 | - **Project Running on IP and Port**
335 |
336 | - Your project is now running on the specified IP and port:
337 |
338 | 
339 |
340 | ### Step 9 : Install NGINX and Configure
341 |
342 | - **Why Use NGINX?**
343 |
344 | 1. Reverse Proxy: NGINX acts as a reverse proxy, allowing you to manage traffic to your Node.js app efficiently. It forwards requests and handles load balancing, improving performance and reliability.
345 | 2. Static File Serving: NGINX is excellent at serving static files (like images, CSS, and JavaScript) quickly and efficiently, freeing up your Node.js application to handle dynamic content.
346 | 3. SSL Termination: NGINX can handle SSL/TLS encryption, allowing secure HTTPS connections while offloading this work from your Node.js application.
347 | 4. Connection Handling: NGINX can handle a large number of concurrent connections, which is beneficial for high-traffic applications, ensuring better resource management.
348 | 5. Caching: NGINX can cache responses to reduce load on your backend and speed up response times for users.
349 |
350 | - **Install NGINX**:
351 |
352 | To install NGINX on your server, run the following command:
353 |
354 | ```bash
355 | sudo apt install nginx
356 | ```
357 |
358 | 
359 |
360 | ---
361 |
362 | - **Configure NGINX**:
363 |
364 | 1. Open the NGINX default site configuration file using `vim` (or any text editor):
365 |
366 | ```bash
367 | sudo vim /etc/nginx/sites-available/default
368 | ```
369 |
370 | 2. Modify the configuration to serve your Node.js application. Update the `server` block as needed (an example config is provided below):
371 |
372 | ```nginx
373 | server_name yourdomain.com www.yourdomain.com;
374 |
375 | location / {
376 | proxy_pass http://localhost:8001; #whatever port your app runs on
377 | proxy_http_version 1.1;
378 | proxy_set_header Upgrade $http_upgrade;
379 | proxy_set_header Connection 'upgrade';
380 | proxy_set_header Host $host;
381 | proxy_cache_bypass $http_upgrade;
382 | }
383 | ```
384 |
385 | - Replace `your-domain.com` with your actual domain or `IP address`.
386 | 
387 |
388 | ---
389 |
390 | - **Enable the configuration and restart NGINX**:
391 |
392 | 1. Check for any syntax errors in your NGINX configuration:
393 |
394 | ```bash
395 | sudo nginx -t
396 | ```
397 |
398 | 2. If there are no errors, restart NGINX to apply the changes:
399 |
400 | ```bash
401 | sudo nginx -s reload
402 |
403 | ```
404 |
405 | ---
406 |
407 | 
408 |
409 | Now, NGINX should be serving your Node.js application. You can access it via your domain or IP.
410 |
411 | ### Step 10 : Add SSL with Let's Encrypt
412 |
413 | - To add SSL with Let's Encrypt, you need to install the Certbot package on your Ubuntu server. Follow these steps:
414 |
415 | 1. **Add the Certbot PPA**:
416 |
417 | ```bash
418 | sudo add-apt-repository ppa:certbot/certbot
419 | ```
420 |
421 | 2. **Update the package list**:
422 |
423 | ```bash
424 | sudo apt-get update
425 | ```
426 |
427 | 3. **Install Certbot and the NGINX plugin**:
428 |
429 | ```bash
430 | sudo apt-get install python3-certbot-nginx
431 | ```
432 |
433 | 4. **Obtain an SSL certificate**:
434 |
435 | Use the following command to configure SSL for your domain:
436 |
437 | ```bash
438 | sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
439 | ```
440 |
441 | - Replace `yourdomain.com` with your actual domain name.
442 |
443 | 5. **Test the renewal process**:
444 |
445 | Certificates from Let's Encrypt are valid for 90 days. To ensure your renewal process works, you can run:
446 |
447 | ```bash
448 | certbot renew --dry-run
449 | ```
450 |
451 | This command simulates the renewal process to verify that it will work when your certificate is close to expiration.
452 |
--------------------------------------------------------------------------------
/src/content/docs/dsa-js/linkedlist.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: JavaScript Linked List Questions Guide
3 | description: Advanced-Level JavaScript Data Structures and Algorithms Questions
4 | ---
5 |
6 | ## Overview
7 |
8 | This guide covers the implementation and operations of different types of linked lists in JavaScript. It serves as a comprehensive reference for understanding and working with linked list data structures.
9 |
10 | ## Definition
11 |
12 | A Linked list is a linear data structure where elements, called **nodes**, are not stored contiguously in memory. Instead, each node contains **data** and a **references** , or link, to the next node in the sequence,
13 |
14 | ## Types of Linked Lists
15 |
16 | ### 1. Singly Linked List
17 |
18 | A singly linked list is a linear data structure where each element (node) contains a data field and a reference (link) to the next node in the sequence.
19 |
20 | #### Core Operations
21 |
22 | - **Push**: Add a new node at the end of the list
23 | - **Pop**: Remove the last node from the list
24 | - **Unshift**: Add a new node at the beginning of the list
25 | - **Shift**: Remove the first node from the list
26 | - **GetFirst**: Retrieve the first node
27 | - **GetLast**: Retrieve the last node
28 | - **Set**: Update the value of a node at a specific position
29 | - **Insert**: Add a new node at a specific position
30 | - **Size**: Get the total number of nodes
31 | - **Clear**: Remove all nodes from the list
32 |
33 | ### 2. Doubly Linked List
34 |
35 | A doubly linked list is an extension of the singly linked list where each node contains references to both the next and previous nodes.
36 |
37 | #### Core Operations
38 |
39 | - **Push**: Add a new node at the end of the list
40 | - **Pop**: Remove the last node from the list
41 | - **Unshift**: Add a new node at the beginning of the list
42 | - **Shift**: Remove the first node from the list
43 |
44 | ### 3. Reverse Linked List
45 |
46 | A specialized operation that reverses the order of nodes in a linked list.
47 |
48 |
49 |
50 | ## 1. Node + LinkedList Class (Singly)
51 |
52 | ### 🧩 Node Class
53 |
54 | ```js
55 | class Node {
56 | constructor(value) {
57 | this.value = value;
58 | this.next = null;
59 | }
60 | }
61 | ```
62 |
63 | ### 🛠 LinkedList Class
64 |
65 | ```js
66 | class LinkedList {
67 | constructor(value) {
68 | this.head = new Node(value);
69 | this.tail = this.head;
70 | this.length = 1;
71 | }
72 |
73 | push(value) {
74 | const newNode = new Node(value);
75 | if (!this.head) {
76 | this.head = newNode;
77 | this.tail = newNode;
78 | } else {
79 | this.tail.next = newNode;
80 | this.tail = newNode;
81 | }
82 | this.length++;
83 | }
84 |
85 | pop() {
86 | if (!this.head) return undefined;
87 | let temp = this.head;
88 | let prev = this.head;
89 | while (temp.next) {
90 | prev = temp;
91 | temp = temp.next;
92 | }
93 | this.tail = prev;
94 | this.tail.next = null;
95 | this.length--;
96 | if (this.length === 0) {
97 | this.head = null;
98 | this.tail = null;
99 | }
100 | return temp;
101 | }
102 |
103 | unShift(value) {
104 | const newNode = new Node(value);
105 | if (!this.head) {
106 | this.head = newNode;
107 | this.tail = newNode;
108 | } else {
109 | newNode.next = this.head;
110 | this.head = newNode;
111 | }
112 | this.length++;
113 | return this;
114 | }
115 |
116 | shift() {
117 | if (!this.head) return undefined;
118 | let temp = this.head;
119 | this.head = this.head.next;
120 | temp.next = null;
121 | this.length--;
122 | if (this.length === 0) this.tail = null;
123 | return temp;
124 | }
125 |
126 | getFirst() {
127 | return this.head;
128 | }
129 |
130 | getLast() {
131 | let temp = this.head;
132 | while (temp && temp.next) {
133 | temp = temp.next;
134 | }
135 | return temp;
136 | }
137 |
138 | get(index) {
139 | let count = 0;
140 | let temp = this.head;
141 | while (temp) {
142 | if (count === index) return temp;
143 | temp = temp.next;
144 | count++;
145 | }
146 | return null;
147 | }
148 |
149 | set(index, value) {
150 | const found = this.get(index);
151 | if (found) {
152 | found.value = value;
153 | return true;
154 | }
155 | return false;
156 | }
157 |
158 | insert(index, value) {
159 | if (index === 0) return this.unShift(value);
160 | if (index === this.length) return this.push(value);
161 | const newNode = new Node(value);
162 | const prev = this.get(index - 1);
163 | if (!prev) return false;
164 | newNode.next = prev.next;
165 | prev.next = newNode;
166 | this.length++;
167 | return true;
168 | }
169 |
170 | size() {
171 | return this.length;
172 | }
173 |
174 | clear() {
175 | this.head = null;
176 | this.tail = null;
177 | this.length = 0;
178 | }
179 | }
180 | ```
181 |
182 | ---
183 |
184 | ## 🧪 Example + Step-by-Step Breakdown
185 |
186 | ```js
187 | const list = new LinkedList(10);
188 | list.push(20);
189 | list.push(30);
190 | list.unshift(5);
191 | list.pop();
192 | list.shift();
193 |
194 | console.log("First Node:", list.getFirst());
195 | console.log("Last Node:", list.getLast());
196 | console.log("Size:", list.size());
197 | list.set(1, 100);
198 | list.insert(1, 50);
199 | list.clear();
200 | ```
201 |
202 | ---
203 |
204 | ### 🧠 Let’s Understand Step by Step
205 |
206 | #### ✅ Step 1: `new LinkedList(10)`
207 |
208 | - List: `10`
209 | - Head = Tail = 10
210 | - Length = 1
211 |
212 | #### ✅ Step 2: `push(20)`
213 |
214 | - List: `10 → 20`
215 | - Tail is now 20
216 | - Length = 2
217 |
218 | #### ✅ Step 3: `push(30)`
219 |
220 | - List: `10 → 20 → 30`
221 | - Tail is now 30
222 | - Length = 3
223 |
224 | #### ✅ Step 4: `unshift(5)`
225 |
226 | - List: `5 → 10 → 20 → 30`
227 | - Head is now 5
228 | - Length = 4
229 |
230 | #### ✅ Step 5: `pop()`
231 |
232 | - Removes 30
233 | - List: `5 → 10 → 20`
234 | - Tail is now 20
235 | - Length = 3
236 |
237 | #### ✅ Step 6: `shift()`
238 |
239 | - Removes 5
240 | - List: `10 → 20`
241 | - Head is now 10
242 | - Length = 2
243 |
244 | #### ✅ Step 7: `getFirst()` → returns `10`
245 |
246 | #### ✅ Step 8: `getLast()` → returns `20`
247 |
248 | #### ✅ Step 9: `size()` → returns `2`
249 |
250 | #### ✅ Step 10: `set(1, 100)`
251 |
252 | - Updates index 1 (which is 20) to 100
253 | - List: `10 → 100`
254 |
255 | #### ✅ Step 11: `insert(1, 50)`
256 |
257 | - Insert 50 at index 1
258 | - List: `10 → 50 → 100`
259 | - Length = 3
260 |
261 | #### ✅ Step 12: `clear()`
262 |
263 | - Empties the list
264 | - List: empty
265 | - Head = Tail = null
266 | - Length = 0
267 |
268 | ---
269 |
--------------------------------------------------------------------------------
/src/content/docs/dsa-js/medium.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: JavaScript Medium Questions
3 | description: Medium-Level JavaScript DSA Questions
4 | ---
5 |
6 | # 1. MaxProfit
7 |
8 | ## Problem Statement
9 |
10 | Imagine you are buying and selling stocks throughout the year. Your task is to find the maximum profit you can make by buying at a low price and selling at a high price **only once**.
11 |
12 | ### Example
13 |
14 | #### Given:
15 |
16 | A list of stock prices for each day:
17 |
18 | ```javascript
19 | [7, 1, 5, 3, 6, 4];
20 | ```
21 |
22 | #### Goal:
23 |
24 | Find the difference between the lowest price at which you could have bought the stock and the highest price at which you could have sold it later.
25 |
26 | ### Solution
27 |
28 | ```javascript
29 | const maxProfit = (prices) => {
30 | let minPrice = prices[0];
31 | let maxProfit = 0;
32 |
33 | for (let i = 1; i < prices.length; i++) {
34 | const currentPrice = prices[i];
35 |
36 | minPrice = Math.min(minPrice, currentPrice);
37 | const potentialProfit = currentPrice - minPrice;
38 | maxProfit = Math.max(maxProfit, potentialProfit);
39 | }
40 |
41 | return maxProfit;
42 | };
43 |
44 | const prices = [7, 1, 5, 3, 6, 4];
45 | const profit = maxProfit(prices);
46 | console.log("Max Profit:", profit); // Output: 5
47 | ```
48 |
49 | ### Explanation
50 |
51 | 1. Start with the first price as the **minimum price**.
52 | 2. Iterate through the list, updating the **minimum price** whenever a lower price is found.
53 | 3. Calculate the potential profit by subtracting the **minimum price** from the current price.
54 | 4. Update the **maximum profit** if the potential profit is greater than the current max.
55 | 5. Return the **maximum profit** found.
56 |
57 | ### Time Complexity
58 |
59 | - **O(n)** → We iterate through the array once.
60 |
61 | ### Space Complexity
62 |
63 | - **O(1)** → Only a few extra variables are used.
64 |
65 | This approach ensures that we find the best profit possible in an optimal way. 🚀
66 |
67 | # 2. Array Chunk
68 |
69 | ## Problem Statement
70 |
71 | Write a function that takes an array and chunk size as input. The function should return a new array where the original array is split into sub-arrays of the specified size.
72 |
73 | ### Example
74 |
75 | #### Given:
76 |
77 | An array and a chunk size:
78 |
79 | ```javascript
80 | chunk([1, 2, 3, 4, 5], 2); // Should return [[1, 2], [3, 4], [5]]
81 | chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // Should return [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
82 | ```
83 |
84 | ### Steps
85 |
86 | 1. create an empty array to hold the chunks
87 | 2. Set a starting index to keep track of where we are in the original array
88 | 3. Loop through the original array as long as the index has not reached the end of the array
89 | 4. Extract a chunk of the desired size from the original array
90 | 5. Add the extracted chunk to the `chunked` array
91 | 6. Move the index forward by the chunk size to get to the next chunk
92 |
93 | The `chunk` function takes an array and a chunk size as input and splits the array into smaller arrays (chunks) of the given size. Let's break it down step by step:
94 |
95 | ### **Code Explanation**
96 |
97 | ```js
98 | function chunk(array, size) {
99 | const chunked = []; // Initialize an empty array to store the chunks
100 | let index = 0; // Start index for slicing
101 |
102 | while (index < array.length) {
103 | // Loop until we reach the end of the array
104 | const chunk = array.slice(index, index + size); // Extract a chunk of the specified size
105 | chunked.push(chunk); // Add the chunk to the result array
106 | index += size; // Move the index forward by the chunk size
107 | }
108 |
109 | return chunked; // Return the array of chunks
110 | }
111 | ```
112 |
113 | ---
114 |
115 | ### **Example Execution**
116 |
117 | ```js
118 | console.log(chunk([1, 2, 3, 4, 5], 2));
119 | ```
120 |
121 | #### **Step-by-step execution:**
122 |
123 | - **Input:** `[1, 2, 3, 4, 5]`, `size = 2`
124 | - **Iteration 1:**
125 |
126 | - `index = 0`
127 | - `chunk = array.slice(0, 2) → [1, 2]`
128 | - `chunked = [[1, 2]]`
129 | - `index += 2 → index = 2`
130 |
131 | - **Iteration 2:**
132 |
133 | - `index = 2`
134 | - `chunk = array.slice(2, 4) → [3, 4]`
135 | - `chunked = [[1, 2], [3, 4]]`
136 | - `index += 2 → index = 4`
137 |
138 | - **Iteration 3:**
139 |
140 | - `index = 4`
141 | - `chunk = array.slice(4, 6) → [5]`
142 | - `chunked = [[1, 2], [3, 4], [5]]`
143 | - `index += 2 → index = 6 (loop stops)`
144 |
145 | - **Final Output:**
146 |
147 | ```js
148 | [[1, 2], [3, 4], [5]];
149 | ```
150 |
151 | ---
152 |
153 | 👉 **Example Outputs:**
154 |
155 | ```js
156 | console.log(chunk([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]
157 | console.log(chunk([1, 2, 3, 4, 5, 6], 3)); // [[1, 2, 3], [4, 5, 6]]
158 | console.log(chunk([1, 2, 3, 4, 5], 4)); // [[1, 2, 3, 4], [5]]
159 | ```
160 |
161 | ### Time Complexity
162 |
163 | - **O(n)** → We process each element in the array once.
164 |
165 | ### Space Complexity
166 |
167 | - **O(n)** → We create a new array containing all the elements from the original array.
168 |
169 | This approach is clean and efficient for dividing an array into chunks of a specified size. 🧩
170 |
171 | ### **Summary**
172 |
173 | This function splits an array into smaller chunks of the specified size. If there are leftover elements that don't fit exactly into a chunk of the given size, they form a smaller chunk at the end.
174 |
175 | # 3. Two Sum Problem
176 |
177 | ## Problem Statement
178 |
179 | The **Two Sum** problem requires finding two numbers in a given list that add up to a specified target number. Additionally, you need to return the indices of these two numbers.
180 |
181 | ## Example
182 |
183 | ```javascript
184 | // Given input
185 | const nums = [2, 7, 11, 15];
186 | const target = 9;
187 |
188 | // Expected Output
189 | // The numbers 2 and 7 add up to 9, and their indices are [0, 1]
190 | ```
191 |
192 | ## Solution Approach
193 |
194 | We can solve this problem using a **brute-force approach** by checking all possible pairs of numbers. This method runs in **O(n²) time complexity**.
195 |
196 | ## Implementation
197 |
198 | ```javascript
199 | function twoSum(nums, target) {
200 | // Loop through the list
201 | for (let i = 0; i < nums.length; i++) {
202 | for (let j = i + 1; j < nums.length; j++) {
203 | // Check if the sum of two numbers equals the target
204 | if (nums[i] + nums[j] === target) {
205 | return [i, j];
206 | }
207 | }
208 | }
209 | return []; // Return empty array if no solution found
210 | }
211 |
212 | // Example usage
213 | const result = twoSum([2, 7, 11, 15], 9);
214 | console.log(result); // Output: [0, 1]
215 | ```
216 |
217 | ## Optimized Approach
218 |
219 | Instead of using nested loops, we can use a **hash map (object in JavaScript)** to store numbers and their indices while iterating through the array. This approach runs in **O(n) time complexity**.
220 |
221 | ### Explanation
222 |
223 | 1. **Initialize a Hash Map:**
224 |
225 | - We create an empty object `map` to store numbers as keys and their indices as values.
226 |
227 | 2. **Iterate Through the Array:**
228 |
229 | - For each number `nums[i]`, calculate its **complement**, which is `target - nums[i]`.
230 | - Check if this **complement** already exists in `map`.
231 |
232 | 3. **Check for Solution:**
233 |
234 | - If the **complement** exists in `map`, it means we have found two numbers that add up to the target.
235 | - Return their indices `[map[complement], i]`.
236 |
237 | 4. **Store the Current Number:**
238 | - If the complement does not exist, store `nums[i]` in `map` with its index `i`.
239 | - This ensures that future iterations can find the required pair.
240 |
241 | ### Code Implementation
242 |
243 | ```javascript
244 | function twoSumOptimized(nums, target) {
245 | let map = {};
246 | for (let i = 0; i < nums.length; i++) {
247 | let complement = target - nums[i];
248 | if (map.hasOwnProperty(complement)) {
249 | return [map[complement], i];
250 | }
251 | map[nums[i]] = i;
252 | }
253 | return [];
254 | }
255 |
256 | // Example usage
257 | const optimizedResult = twoSumOptimized([2, 7, 11, 15], 9);
258 | console.log(optimizedResult); // Output: [0, 1]
259 | ```
260 |
261 | ## Complexity Analysis
262 |
263 | | Approach | Time Complexity | Space Complexity |
264 | | --------------- | --------------- | ---------------- |
265 | | Brute Force | O(n²) | O(1) |
266 | | Hash Map Method | O(n) | O(n) |
267 |
268 | ## Usage Instructions
269 |
270 | 1. Copy and paste the function into your JavaScript project.
271 | 2. Call `twoSum(nums, target)` with an array of numbers and a target value.
272 | 3. The function will return an array containing the indices of the two numbers that add up to the target.
273 | 4. Use `console.log()` to see the result.
274 |
275 | ## Conclusion
276 |
277 | The **Two Sum** problem is a common algorithmic challenge. The brute-force approach works but is slow for large lists. Using a hash map significantly improves efficiency.
278 | Happy coding! 🚀
279 |
--------------------------------------------------------------------------------
/src/content/docs/dsa-js/questions.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: JavaScript Questions
3 | description: A beginner-friendly JavaScript Dsa Questions
4 | ---
5 |
6 | # 1. Palindrome Checker
7 |
8 | Given an integer x, return true if x is a
9 | palindrome, and false otherwise.
10 |
11 | - Example 1:
12 |
13 | Input: x = 121
14 | Output: true
15 | Explanation: 121 reads as 121 from left to right and from right to left.
16 |
17 | - Example 2:
18 |
19 | Input: x = -121
20 | Output: false
21 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
22 |
23 | - Example 3:
24 |
25 | Input: x = 10
26 | Output: false
27 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
28 |
29 | ## Function Definition
30 |
31 | ```javascript
32 | /**
33 | * Function to check if a number is a palindrome.
34 | * @param {number} x - The integer to check.
35 | * @returns {boolean} - Returns true if the integer is a palindrome, otherwise false.
36 | */
37 | const isPalindrome = function (x) {
38 | return x === +x.toString().split("").reverse().join("");
39 | };
40 |
41 | // Example Usage
42 | const res = isPalindrome(10);
43 | console.log(res); // Output: false
44 | ```
45 |
46 | # 2. Fibonacci Number
47 |
48 | **Difficulty:** Easy
49 |
50 | ### Problem Description
51 |
52 | The Fibonacci numbers, commonly denoted F(n), form a sequence called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
53 |
54 | - F(0) = 0, F(1) = 1
55 | - F(n) = F(n - 1) + F(n - 2), for n > 1.
56 |
57 | Given `n`, calculate F(n).
58 |
59 | ### Example 1
60 |
61 | **Input : `n = 2`**
62 | **Output : `1`**
63 | **Explanation : `F(2) = F(1) + F(0) = 1 + 0 = 1.`**
64 |
65 | ### Example 2
66 |
67 | **Input : `n = 3`**
68 | **Output : `2`**
69 | **Explanation : `F(3) = F(2) + F(1) = 1 + 1 = 2.`**
70 |
71 | ### Example 3
72 |
73 | **Input : `n = 4`**
74 | **Output : `3`**
75 | **Explanation : `F(4) = F(3) + F(2) = 2 + 1 = 3.`**
76 |
77 | ### Function Definition
78 |
79 | ```javascript
80 | const fib = function (n) {
81 | if (n <= 1) return n;
82 |
83 | return fib(n - 1) + fib(n - 2);
84 | };
85 | ```
86 |
87 | ### Explanation
88 |
89 | 1. Base Case :
90 |
91 | - The function starts by checking if `n` is less than or equal to 1.
92 | - If `n` is 0 , the function return 0
93 | - If `n` is 1, the function return 1
94 | - These are the base cases for the Fibonacci sequence and represent the first two numbers in the sequence.
95 |
96 | 2. Recursive Case :
97 |
98 | - If `n` is greater than 1, the function calls itself twice, once with `
99 |
100 | # 3. Missing Number
101 |
102 | This algorithm is designed to find the missing number in an array of integers where the numbers range from `0` to `n`, but one number is missing.
103 |
104 | ### Code:
105 |
106 | ```javascript
107 | /**
108 | * @param {number[]} nums
109 | * @return {number}
110 | */
111 | const missingNumber = function (nums) {
112 | const expectedSum = (nums.length * (nums.length + 1)) / 2;
113 | return expectedSum - nums.reduce((acc, num) => acc + num, 0);
114 | };
115 | ```
116 |
117 | ### Step-by-Step Explanation :
118 |
119 | - Step 1: Calculating Expected Sum
120 |
121 | ```js
122 | const expectedSum = (nums.length * (nums.length + 1)) / 2;
123 | ```
124 |
125 | 
126 |
127 | - Step 2: Calculating Actual Sum
128 |
129 | ```js
130 | nums.reduce((acc, num) => acc + num, 0);
131 | ```
132 |
133 | - The reduce function is used to sum all the numbers present in the array.
134 | - For example, if the array is `[0, 1, 3, 4]`, the sum will be : _`0+1+3+4=8`_
135 |
136 | - Step 3: Finding the Missing Number
137 |
138 | ```js
139 | return expectedSum - nums.reduce((acc, num) => acc + num, 0);
140 | ```
141 |
142 | - The missing number is calculated by subtracting the actual sum from the expected sum.
143 | - In the example above, if the expected sum is`15`and the actual sum is `8`, then the missing number is: _`15−8=7`_
144 |
145 | #### Summary :
146 |
147 | - Expected Sum: We calculate the expected sum for numbers from `0` to `n` using the formula` n \* (n + 1) / 2`.
148 | - Actual Sum: Using the `reduce` function, we calculate the sum of the numbers present in the array.
149 | - Missing Number: The difference between the expected sum and the actual sum gives the missing number.
150 |
151 |
152 |
153 | ---
154 |
155 | ## 4. Capitalize Sentence
156 |
157 | ### **Problem:**
158 | Given a sentence, capitalize the first letter of each word.
159 |
160 | ### **Solution:**
161 | ```javascript
162 | function capitalizeSentence(sentence) {
163 | return sentence
164 | .split(' ')
165 | .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
166 | .join(' ');
167 | }
168 | ```
169 |
170 | ### **Example:**
171 | ```javascript
172 | console.log(capitalizeSentence("hello world! this is javascript."));
173 | // Output: "Hello World! This Is Javascript."
174 | ```
175 |
176 | ---
177 |
178 | ## 5. FizzBuzz
179 |
180 | ### **Problem:**
181 | Print numbers from `1` to `n`. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For numbers divisible by both 3 and 5, print "FizzBuzz".
182 |
183 | ### **Solution:**
184 | ```javascript
185 | function fizzBuzz(n) {
186 | for (let i = 1; i <= n; i++) {
187 | if (i % 3 === 0 && i % 5 === 0) {
188 | console.log("FizzBuzz");
189 | } else if (i % 3 === 0) {
190 | console.log("Fizz");
191 | } else if (i % 5 === 0) {
192 | console.log("Buzz");
193 | } else {
194 | console.log(i);
195 | }
196 | }
197 | }
198 | ```
199 |
200 | ### **Example:**
201 | ```javascript
202 | fizzBuzz(20);
203 | ```
204 |
205 | ---
206 |
207 | ## 6. Maximum Profit (Stock Trading)
208 |
209 | ### **Problem:**
210 | Given an array of stock prices, find the maximum profit you can achieve by buying and selling once.
211 |
212 | ### **Solution:**
213 | ```javascript
214 | function maxProfit(prices) {
215 | let minPrice = Infinity, maxProfit = 0;
216 | for (let price of prices) {
217 | minPrice = Math.min(minPrice, price);
218 | maxProfit = Math.max(maxProfit, price - minPrice);
219 | }
220 | return maxProfit;
221 | }
222 | ```
223 |
224 | ### **Example:**
225 | ```javascript
226 | console.log(maxProfit([7, 1, 5, 3, 6, 4])); // Output: 5 (Buy at 1, Sell at 6)
227 | console.log(maxProfit([7, 6, 4, 3, 1])); // Output: 0 (No profit possible)
228 | ```
229 |
230 | ---
231 |
232 |
233 |
234 | # 7. Find Student in Array
235 |
236 | This algorithm is designed to search for a student's name in an array of student names. If the name is found, it will print the student's name.
237 |
238 | ### Problem Description
239 |
240 | Given an array of student names and a target name to search for, check if the name exists in the array. If found, print the name; otherwise, do nothing.
241 |
242 | ### Example 1
243 |
244 | **Input :**
245 |
246 | ```js
247 | const studentDB = ["Saurabh", "Banti", "Raju", "Rajesh", "Dipali"];
248 |
249 | findStudent(studentData, "Saurabh");
250 | ```
251 |
252 | Output :
253 |
254 | ```js
255 | Saurabh
256 | ```
257 |
258 | **Explanation :** The name "Saurabh" is found in the array, so it is printed.
259 |
260 | ### Example 2
261 |
262 | **Input :**
263 |
264 | ```js
265 | findStudent(studentData, "Amit");
266 | ```
267 |
268 | Output :
269 |
270 | ```js
271 | (No Output)
272 | ```
273 |
274 | **Explanation :** The name "Amit" is not found, so nothing is printed.
275 |
276 | ### Function Definition
277 |
278 | ```js
279 | /**
280 | * Function to find and print a student's name from an array.
281 | * @param {string[]} allStudents - Array of student names.
282 | * @param {string} studentName - The name to search for.
283 | */
284 |
285 | const findStudentName = (data, name) => {
286 | for (let i = 0; i < data.length; i++) {
287 | if (data[i] === name) {
288 | return data[i];
289 | }
290 | }
291 | return false;
292 | };
293 |
294 | // console.log(findStudentName(studentDB, "Raju"));
295 |
296 | ### Step-by-Step Explanation:
297 |
298 | 1. Input Parameters:
299 |
300 | * allStudents: An array containing the names of all students.
301 | * studentName: The name of the student to find.
302 |
303 |
304 | 2. For Loop:
305 |
306 | ```js
307 | for (let i = 0; i < data.length; i++) {
308 | if (data[i] === name) {
309 | return data[i];
310 | }
311 | }
312 | ```
313 |
314 | * The loop starts at index 0 and continues until the end of the array.
315 | * i is used as the index to access each student's name.
316 |
317 | 3. Condition Check:
318 |
319 | ```js
320 | if (data[i] === name) {
321 | return data[i];
322 | }
323 | ```
324 |
325 | * Checks if the current name in the array is equal to the studentName.
326 | * If a match is found, it prints the name using console.log.
327 |
328 | 4. Output:
329 |
330 | * If the name is found, it prints the student's name.
331 | * If the name is not found, nothing is printed.
332 |
333 | #### Example Usage:
334 |
335 | ```js
336 | const studentDB = ["Saurabh", "Banti", "Raju", "Rajesh", "Dipali"];
337 |
338 | findStudent(studentData, "Saurabh"); // Output: Saurabh
339 | findStudent(studentData, "Amit"); // No Output
340 | ```
341 |
342 | #### Summary:
343 | * The function iterates through the array using a for loop.
344 | * It checks each name to see if it matches the given studentName.
345 | * If a match is found, it prints the name.
346 | * If no match is found, the loop ends without any output.
--------------------------------------------------------------------------------
/src/content/docs/index.mdx:
--------------------------------------------------------------------------------
1 | ---
2 | title: Welcome to Guide Docs
3 | description: Get started building your docs site with Starlight.
4 | template: splash
5 | hero:
6 | tagline: Next-gen documentation that builds reading habits into your workflow.
7 | image:
8 | file: ../../assets/houston.webp
9 | actions:
10 | - text: Check out the docs
11 | link: /intro/intro/
12 | icon: right-arrow
13 | variant: primary
14 | ---
15 |
16 | import { Card, CardGrid } from '@astrojs/starlight/components';
17 |
18 | ## Cooming soon
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/content/docs/intro/intro.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Introduction to Guide Docs
3 | description: A beginner-friendly guide to learning HTML basics.
4 | ---
5 |
6 | This repository provides a beginner-friendly guide to learning HTML, aimed at helping you understand the basics of web development.
7 |
8 | ## Contents
9 |
10 | - **Guides**: Step-by-step instructions to accomplish specific tasks.
11 | - **Further Reading**: Additional resources to deepen your understanding.
12 |
13 | ## Getting Started
14 |
15 | To get started with HTML, follow these steps:
16 |
17 | 1. **Clone the Repository**: Download or clone this repository to your local machine.
18 |
19 | 2. **Navigate to the Guide**: Open the guide titled `Introduction_to_HTML.md` to begin learning.
20 |
21 | 3. **Follow Along**: Read each section carefully and try out the examples provided.
22 |
23 | ## How to Use
24 |
25 | - **Read the Guide**: Start with the `Introduction_to_HTML.md` file to understand the basics of HTML.
26 |
27 | - **Explore Further**: Check out additional resources in the "Further Reading" section for more in-depth knowledge.
28 |
29 | ## Contributing
30 |
31 | Contributions to improve this guide are welcome! If you have suggestions or find errors, please submit an issue or a pull request.
32 |
33 | ## License
34 |
35 | This project is licensed under the MIT License - see the LICENSE file for details.
36 |
--------------------------------------------------------------------------------
/src/content/docs/javaScript/javascript_datatypes.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: What is Datatypes
3 | description: discussion about Datatypes
4 | ---
5 |
6 | # Datatype
7 |
8 | A **datatype** is a classification that specifies the type of value a variable can hold in programming. It defines the kind of data that can be stored and manipulated within a program, such as numbers, strings, or objects.
9 |
10 | **There are 2 types of datatypes -**
11 |
12 | ### Primitive Data-Types
13 |
14 | Primitive data types are the *most basic* types of data that JavaScript supports.
15 |
16 | 1. **String :**
17 |
18 | * Represents textual data.
19 | * Enclosed in **single quotes** (' '), **double quotes** (" "), or **backticks** (`) for template literals.
20 |
21 | * **Example :**
22 |
23 | ```js
24 | let name = 'Yogita';
25 | let greeting = "Hello, world!";
26 | let message = `Welcome, ${name}!`;
27 | ```
28 |
29 | 2. **Number :**
30 |
31 | * Represents numeric values.
32 | * Includes _integers_ and _floating-point_ numbers.
33 |
34 | * **Example:**
35 |
36 | ```js
37 | let age = 25;
38 | let price = 19.99;
39 | ```
40 |
41 | 3. **Boolean :**
42 |
43 | * Represents a logical entity and can have two values: **true** and **false**.
44 |
45 | * **Example:**
46 |
47 | ```js
48 | let isActive = true;
49 | let isCompleted = false;
50 | ```
51 |
52 | 4. **Undefined**
53 |
54 | * A variable that has been declared but *not assigned* a value.
55 |
56 | **Example :**
57 |
58 | ```js
59 | let notDefined;
60 | console.log(notDefined); // undefined
61 | ```
62 |
63 | 5. **Null :**
64 |
65 | * Represents the intentional absence of any object value.
66 |
67 | **Example :**
68 |
69 | ```js
70 | let emptyValue = null;
71 | ```
72 |
73 | 6. **Symbol :**
74 |
75 | * Introduced in ES6, represents a *unique* and *immutable* identifier.
76 |
77 | **Example :**
78 |
79 | ```js
80 | let symbol1 = Symbol('description');
81 | let symbol2 = Symbol('description');
82 | console.log(symbol1 === symbol2); // false
83 | ```
84 |
85 | 7. **BigInt :**
86 |
87 | * Introduced in ES2020, represents whole numbers larger than the Number type can safely represent.
88 |
89 | **Example :**
90 |
91 | ```js
92 | let bigNumber = BigInt(1234567890123456789012345678901234567890n);
93 | ```
94 |
95 | ### Non-Primitive Data-Types
96 |
97 | Non-primitive data types, also known as reference types, include:
98 |
99 | 1. **Object :**
100 |
101 | * Used to store collections of data and more complex entities.
102 |
103 | * **Example :**
104 |
105 | ```js
106 | let person = {
107 | name: 'John',
108 | age: 30,
109 | isActive: true
110 | };
111 | ```
112 |
113 | 2. **Array :**
114 |
115 | * A special type of object used to store ordered collections.
116 |
117 | * **Example :**
118 |
119 | ```js
120 | let numbers = [1, 2, 3, 4, 5];
121 | ```
122 |
123 | 3. **Function :**
124 |
125 | * Functions are a special type of object callable with arguments.
126 |
127 | * **Example :**
128 |
129 | ```js
130 | function greet(name) {
131 | return `Hello, ${name}!`;
132 | }
133 | ```
134 |
135 | 4. **Date :**
136 |
137 | * A built-in object for handling dates and times.
138 |
139 | * **Example :**
140 |
141 | ```js
142 | let today = new Date();
143 | ```
144 |
145 | 5. **RegExp :**
146 |
147 | * Regular expressions, used for pattern matching within strings.
148 |
149 | * **Example:**
150 |
151 | ```js
152 | let regex = /hello/i;
153 | ```
154 |
155 | 6. **Map and Set :**
156 |
157 | * **Map:** An object that holds key-value pairs and remembers the original insertion order of the keys.
158 |
159 | * **Example :**
160 |
161 | ```js
162 | let map = new Map();
163 | map.set('name', 'John');
164 | map.set('age', 30);
165 | ```
166 |
167 | * **Set :** An object that lets you store unique values of any type, whether primitive values or object references.
168 |
169 | * **Example :**
170 | ```js
171 | let set = new Set([1, 2, 3, 4, 5]);
172 | ```
173 |
174 |
175 |
176 |
177 |
178 | **Happy Coding Guys!!**
179 |
--------------------------------------------------------------------------------
/src/content/docs/javaScript/javascript_introduction.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: What is JavaScript?
3 | description: discussion about JS
4 | ---
5 |
6 | - JavaScript is a high-level language used to make websites dynamic. It runs in the user’s browser, allowing for interactive features like form checks and live updates. JavaScript works on both the client side and server side with tools like Node.js. It also has many frameworks and libraries, like React and Angular, to make development easier.
7 |
8 | - JavaScript mainly runs in web browsers, which have built-in engines to interpret and execute the code. But JavaScript isn’t just for web browsers; it can also run in environments like Node.js. Node.js allows JavaScript to run on servers and outside the browser.
9 |
10 | **Key Features of JavaScript:**
11 |
12 | - Dynamic Typing
13 | - Event-Driven Programming
14 | - First-Class Functions
15 | - Prototypal Inheritance
16 | - Asynchronous Programming
17 | - Rich Standard Library
18 | - Cross-Platform compatibility
19 |
20 | **Dynamic Typing:** JavaScript is a dynamically typed language, meaning variable types are determined at runtime.
21 |
22 | **Event-Driven Programming:** JavaScript supports event-driven programming, allowing developers to create responsive applications.
23 |
24 | **First-Class Functions:** Functions in JavaScript are first-class objects, meaning they can be stored in variables, passed as arguments, and returned from other functions.
25 |
26 | **Prototypal Inheritance:** JavaScript uses prototypal inheritance, where objects inherit properties directly from other objects.
27 |
28 | **Asynchronous Programming:** JavaScript supports asynchronous programming, allowing for non-blocking operations with features like `callbacks`, `promises`, and `async/await`.
29 |
30 | **Rich Standard Library:** JavaScript provides a rich standard library, including built-in objects and functions for manipulating data, working with the DOM, and handling events.
31 |
32 | **Cross-Platform:** JavaScript runs on multiple platforms, including web `browsers`, `servers`, and even `mobile devices`.
33 |
--------------------------------------------------------------------------------
/src/content/docs/javaScript/javascript_rest_and_spread_operator.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Rest and Spread Operator in JS
3 | description: discussion about Rest and Spread Operator
4 | ---
5 |
6 | The **rest** and **spread** operators in JavaScript are represented by three **dots (...)**. Despite having similar syntax, they serve different purposes depending on the context in which they are used.
7 |
8 | ### Rest Operator (...)
9 |
10 | The **rest** operator allows you to collect the remaining elements of an array or object into a new array or object. It is used in function parameters or destructuring assignments to gather the rest of the elements that are not explicitly listed.
11 |
12 | #### Rest in Function Parameters
13 |
14 | The **rest** operator is commonly used when you want a function to accept an indefinite number of arguments and group them into an array.
15 |
16 | ```js
17 | function sum(...numbers) {
18 | return numbers.reduce((acc, curr) => acc + curr, 0);
19 | }
20 |
21 | console.log(sum(1, 2, 3)); // Output: 6
22 | console.log(sum(4, 5, 6, 7)); // Output: 22
23 | ```
24 |
25 | Here, **...numbers** collects all arguments passed to the **sum** function into an array named **numbers**.
26 |
27 | #### Rest in Array Destructuring
28 |
29 | The **rest** operator can also be used to gather the remaining elements of an array after some have been destructured.
30 |
31 | ```javascript
32 | const [first, second, ...rest] = [1, 2, 3, 4, 5];
33 | console.log(first); // Output: 1
34 | console.log(second); // Output: 2
35 | console.log(rest); // Output: [3, 4, 5]
36 | ```
37 |
38 | Here, **first** and **second** get the first two elements, and **rest** collects the remaining elements into an array.
39 |
40 | #### Rest in Object Destructuring
41 |
42 | Similarly, in object destructuring, you can use the **rest** operator to gather remaining properties into a new object.
43 |
44 | ```javascript
45 | const user = { name: "John", age: 30, country: "USA" };
46 | const { name, ...rest } = user;
47 | console.log(name); // Output: John
48 | console.log(rest); // Output: { age: 30, country: 'USA' }
49 | ```
50 |
51 | In this case, the `name` property is extracted, and the rest of the properties are gathered into a new object.
52 |
53 | ### Spread Operator (...)
54 |
55 | The **spread** operator is used to spread out elements of an array or object into individual elements. It allows you to copy or combine arrays and objects or to pass elements of an array as individual arguments to a function.
56 |
57 | #### Spread in Arrays
58 |
59 | The **spread** operator can be used to expand an array's elements into a new array.
60 |
61 | ```javascript
62 | const arr1 = [1, 2, 3];
63 | const arr2 = [4, 5, 6];
64 | const combined = [...arr1, ...arr2];
65 | console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
66 | ```
67 |
68 | Here, `...arr1` and `...arr2` spread the elements of both arrays into the new combined array.
69 |
70 | #### Spread in Function Arguments
71 |
72 | The **spread** operator allows an array to be passed as individual arguments to a function.
73 |
74 | ```javascript
75 | function add(a, b, c) {
76 | return a + b + c;
77 | }
78 |
79 | const numbers = [1, 2, 3];
80 | console.log(add(...numbers)); // Output: 6
81 | ```
82 |
83 | Here, **...numbers** spreads the array elements as individual arguments to the add function.
84 |
85 | #### Spread in Objects
86 |
87 | You can also use the spread operator to clone or merge objects.
88 |
89 | ```javascript
90 | const user1 = { name: "Alice", age: 25 };
91 | const user2 = { country: "UK" };
92 | const mergedUser = { ...user1, ...user2 };
93 | console.log(mergedUser); // Output: { name: 'Alice', age: 25, country: 'UK' }
94 | ```
95 |
96 | In this case, `...user1` and `...user2` spread the properties of both objects into the new mergedUser object.
97 |
98 | #### Spread for Copying Arrays or Objects
99 |
100 | The **spread** operator provides an easy way to create a shallow copy of an array or object.
101 |
102 | ```javascript
103 | const originalArray = [1, 2, 3];
104 | const copyArray = [...originalArray];
105 | console.log(copyArray); // Output: [1, 2, 3]
106 |
107 | const originalObject = { name: "Bob", age: 40 };
108 | const copyObject = { ...originalObject };
109 | console.log(copyObject); // Output: { name: 'Bob', age: 40 }
110 | ```
111 |
112 | **Summary of Differences:**
113 |
114 | #### Rest Operator (...)
115 |
116 | - Gathers elements into an array or object.
117 | - Commonly used in function parameters and destructuring assignments.
118 |
119 | #### Spread Operator (...)
120 |
121 | - Spreads elements of an array or object.
122 | - Used to expand arrays into individual elements, pass arguments, or merge objects.
123 | - These two operators are incredibly useful for writing clean and flexible code in JavaScript!
124 |
125 | **Rest and Spread operators are same?**
126 |
127 | No, the rest and spread operators are not the same, even though they use the same ... syntax. The key difference lies in how and where they are used.
128 |
129 | **Key Differences:**
130 |
131 | **1. Purpose:**
132 |
133 | - The rest operator is used to gather or collect multiple elements into a single array or object.
134 |
135 | - The spread operator is used to spread or expand an array or object into individual elements.
136 |
137 | **2. Context of Use:**
138 |
139 | - The rest operator is used in function parameter lists and in destructuring assignments to gather remaining elements.
140 |
141 | - **Example:** Gathering remaining function arguments.
142 |
143 | - The spread operator is used when calling functions, in array literals, or object literals to expand an array/object into individual items.
144 |
145 | - **Example:** Spreading array elements or object properties.
146 |
147 | **3. Use Cases:**
148 |
149 | - **Rest:**
150 |
151 | - Collecting arguments in a function (...args).
152 |
153 | - Collecting remaining array elements or object properties when destructuring.
154 |
155 | - **Spread:**
156 |
157 | - Spreading array elements into function arguments (...array).
158 | - Creating a new array by combining others or copying one.
159 | - Merging objects.
160 |
161 | **Visual Comparison:**
162 |
163 | - **Rest Operator** (Collects elements into an array/object):
164 |
165 | ```javascript
166 | function demoRest(...args) {
167 | console.log(args); // ['a', 'b', 'c']
168 | }
169 | demoRest("a", "b", "c");
170 | ```
171 |
172 | - **Spread Operator** (Expands an array/object):
173 |
174 | ```javascript
175 | const arr = ["a", "b", "c"];
176 | console.log(...arr); // 'a' 'b' 'c'
177 | ```
178 |
179 | **In summary :**
180 |
181 | - **Rest** gathers elements into a new collection (used in destructuring or function parameters).
182 |
183 | - **Spread** expands elements from a collection (used to copy, combine arrays/objects, or pass multiple arguments).
184 |
--------------------------------------------------------------------------------
/src/content/docs/javaScript/javascript_stack_and_heap_memory.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Stack and Heap Memory in JS
3 | description: discussion about stack and heap memory
4 | ---
5 |
6 | ### There are two types of memories.
7 |
8 | **1. Stack Memory:**
9 |
10 | - **Definition:** The stack is a region of memory used for static storage. It stores primitive data types (such as `number`, `string`, `boolean`, `null`, `undefined`, `symbol`, and `bigint`) and the reference to objects and functions.
11 | - **Characteristics:**
12 |
13 | - **Fixed Size:** The stack has a fixed size, so it can fill up quickly, leading to a "stack overflow" if too many items are pushed onto the stack.
14 | - **LIFO (Last In, First Out):** Memory is allocated and freed in a strict order, following the LIFO principle.
15 | - **Fast Access:** The stack allows for quick allocation and deallocation of memory, making it faster compared to the heap.
16 | - **Function Call Execution:** Function calls, along with their local variables, are stored on the stack. When a function is called, a new stack frame is created, and it is destroyed when the function completes.
17 |
18 | - **Example:**
19 | ```javascript
20 | function greet() {
21 | let name = "Yogita"; // 'name' is stored in the stack
22 | console.log("Hello, " + name);
23 | }
24 | greet();
25 | ```
26 | - Here, the string `"Yogita"` is stored directly in the stack because it's a primitive value.
27 |
28 | **2. Heap Memory:**
29 |
30 | - **Definition:** The heap is a region of memory used for dynamic storage. It stores objects, arrays, and functions. In JavaScript, anything that is not a primitive value is stored in the heap.
31 | - **Characteristics:**
32 |
33 | - **Dynamic Size:** The heap has a larger, flexible size compared to the stack, allowing for more complex data structures to be stored.
34 | - **Slower Access:** Accessing data in the heap is slower because of the need to manage memory dynamically, and the data is accessed via references.
35 | - **Garbage Collection:** JavaScript uses a garbage collector to manage memory in the heap, automatically freeing up memory that is no longer in use.
36 |
37 | - **Example:**
38 | ```javascript
39 | function createUser() {
40 | let user = {
41 | name: "Yogita", // 'user' is a reference stored in the stack, but the object is stored in the heap
42 | age: 23,
43 | };
44 | return user;
45 | }
46 | let user1 = createUser();
47 | ```
48 | - In this example, the object `{ name: "Yogita", age: 23 }` is stored in the heap, while the reference to this object is stored in the stack.
49 |
50 | **Summary:**
51 |
52 | - **Stack:** Stores primitive data types and references. It has a fixed size and operates in a LIFO manner.
53 | - **Heap:** Stores objects, arrays, and functions. It has dynamic sizing and is managed by garbage collection.
54 |
55 | Understanding the distinction between stack and heap memory is important for optimizing performance and avoiding common issues like memory leaks in JavaScript applications.
56 |
--------------------------------------------------------------------------------
/src/content/docs/javaScript/javascript_variables.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Variables in JS
3 | description: discussion about variable
4 | ---
5 |
6 | Variables allow you to **store** and **manipulate data** in your programs.
7 |
8 | - There are three ways to declared the variables : `let`, `const` and `var`.
9 |
10 | ### Variable Declaration with let
11 |
12 | In JavaScript, when you declare a variable using the `let` keyword, you can reassign its value. This means that after the initial assignment, you can change the value of the variable to something else later in your code.
13 |
14 | **Syntax :**
15 |
16 | ```js
17 | let variable_name;
18 | ```
19 |
20 | **How to create variable using `let` keyword?**
21 |
22 | ```js
23 | let myvariable;
24 | ```
25 |
26 | **Example :**
27 |
28 | ```js
29 | let x = 10;
30 | console.log(x); // Output: 10
31 |
32 | x = 20;
33 | console.log(x); // Output: 20
34 | ```
35 |
36 | ### Variable Declaration with `const`
37 |
38 | In JavaScript, when you declare a variable using the `const` keyword, you cannot reassign its value. This means that once a value is assigned to a const variable, it cannot be changed.
39 |
40 | **Syntax :**
41 |
42 | ```js
43 | const variable_name;
44 | ```
45 |
46 | **Example :**
47 |
48 | ```js
49 | const x = 10;
50 | console.log(x); // Output: 10
51 | ```
52 |
53 | ### Variable Declaration with `var`
54 |
55 | In JavaScript, when you declare a variable using the `var` keyword, you can reassign its value, similar to `let`. However, there are important differences regarding scope and hoisting.
56 |
57 | **Example :**
58 |
59 | ```js
60 | // Declaring a variable using var
61 | var greeting = "Hello, World!";
62 |
63 | // Using the variable
64 | console.log(greeting); // Outputs: Hello, World!
65 | ```
66 |
67 | :::danger
68 | Modern JavaScript often uses `let` and `const` instead of `var` because they have block scope and avoid some of the pitfalls of var.
69 | :::
70 |
71 | ### Difference between const, var and let
72 |
73 | | Feature | var | let | const |
74 | | -------------------------- | ---------------------------------------------- | --------------------------------------- | -------------------------------------------------------- |
75 | | Scope | Function-scoped | Block-scoped | Block-scoped |
76 | | Re-assignment | Can be re-assigned and re-declared. | Can be re-assigned, but not re-declared. | Cannot be re-assigned or re-declared. |
77 | | Hoisting | Hoisted to the top of function. | Hoisted to the top of block. | Hoisted to the top of block. |
78 | | Initialization Requirement. | Can be declared without initialization. | Needs to be initialized before use. | Needs to be initialized before use. |
79 | | Use Cases. | Legacy code compatibility, less strict scoping. | Preferred for variable. scoping clarity. | Preferred for constants and values that shouldn't change. |
80 |
81 | **Happy learning! Happy Coding!**
82 |
--------------------------------------------------------------------------------
/src/content/docs/javaScript/jsvar.md:
--------------------------------------------------------------------------------
1 | ---
2 | title : "JS Variable"
3 | description : "JS Variable"
4 | ---
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/1.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/10.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/11.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/12.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/13.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/14.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/15.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/16.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/17.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/17.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/2.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/21.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/22.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/22.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/23.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/23.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/24.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/25.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/25.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/26.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/26.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/27.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/27.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/28.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/28.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/29.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/29.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/3.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/30.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/30.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/4.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/5.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/6.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/7.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/8.png
--------------------------------------------------------------------------------
/src/content/docs/main/aws/ec2/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/aws/ec2/9.png
--------------------------------------------------------------------------------
/src/content/docs/main/dsa-js/dsa-js-calculate-form-natural-number.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/dsa-js/dsa-js-calculate-form-natural-number.png
--------------------------------------------------------------------------------
/src/content/docs/main/python/python1.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/python/python1.jpeg
--------------------------------------------------------------------------------
/src/content/docs/main/python/python_inner_working2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/python/python_inner_working2.png
--------------------------------------------------------------------------------
/src/content/docs/main/typescript/typescript-inner-working-guide-and-grow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guide-and-Grow/guide-docs/7aa4334ce9c1a360544fbcc6d637642e0832cf0b/src/content/docs/main/typescript/typescript-inner-working-guide-and-grow.png
--------------------------------------------------------------------------------
/src/content/docs/node/node.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: What is Node.js?
3 |
4 | description: Discussion about Node
5 | ---
6 |
7 |
8 | ## Description
9 | Node.js® is a free, open-source, cross-platform JavaScript runtime environment that enables developers to create servers, web applications, command-line tools, and scripts. It allows JavaScript to run on the server, making it fast and efficient with its event-driven, non-blocking model. Node.js is ideal for building web servers, APIs, and real-time applications. Additionally, Node.js simplifies package management with npm.
10 |
11 | ## Key Features
12 | - **JavaScript on the Server**: Run JavaScript code outside the browser.
13 | - **Event-Driven**: Handles multiple connections efficiently.
14 | - **Non-Blocking I/O**: Improves performance by handling requests asynchronously.
15 | - **Cross-Platform**: Works on Windows, macOS, and Linux.
16 | - **Rich Ecosystem**: Thousands of packages available via npm.
17 |
18 | ## How to Install Node.js
19 |
20 | ### Step 1: Download Node.js
21 |
22 | 1. **Visit the Official Node.js Website**: [Node.js Download Page](https://nodejs.org/en/download/)
23 | 2. **Choose the Correct Version**: You will see two versions available: LTS (Long Term Support) and Current.
24 | - For most users, the LTS version is recommended.
25 |
26 | ### Step 2: Install Node.js
27 |
28 | #### Windows
29 |
30 | 1. **Download the Installer**: Click on the **Windows Installer** button to download the `.msi` installer.
31 | 2. **Run the Installer**: Double-click the downloaded installer file.
32 | 3. **Follow the Setup Wizard**:
33 | - Click **"Next"** to accept the default settings.
34 | - Optionally, check the box to install the necessary tools for Node.js and npm (recommended).
35 | 4. **Complete the Installation**: Click **"Install"** and wait for the installation to complete.
36 | 5. **Finish Installation**: Click **"Finish"** when the installation is done.
37 |
38 | #### macOS
39 |
40 | 1. **Download the Installer**: Click on the **macOS Installer** button to download the `.pkg` installer.
41 | 2. **Run the Installer**: Double-click the downloaded installer file.
42 | 3. **Follow the Setup Wizard**:
43 | - Click **"Continue"** to proceed with the installation.
44 | - Agree to the software license agreement.
45 | 4. **Complete the Installation**: Click **"Install"** and enter your system password when prompted.
46 | 5. **Finish Installation**: Click **"Close"** when the installation is done.
47 |
48 | #### Linux
49 |
50 | 1. **Download and Install Using Package Manager**:
51 | - For Ubuntu/Debian-based systems, open a terminal and run:
52 | ```bash
53 | sudo apt update
54 | sudo apt install nodejs npm
55 | ```
56 | - For Fedora-based systems, open a terminal and run:
57 | ```bash
58 | sudo dnf install nodejs npm
59 | ```
60 | - For other distributions, refer to the [Node.js Installation Guide](https://nodejs.org/en/download/package-manager/).
61 |
62 | ## Verify Installation
63 |
64 | To ensure Node.js and npm are installed correctly, open a terminal or command prompt and run:
65 |
66 | ```bash
67 | node -v
68 | npm -v
69 |
70 | ```
71 | happy codding !
--------------------------------------------------------------------------------
/src/content/docs/python/data-types-python.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Data Types in Python
3 | description: Data types are the classification or categorization of data items. The data items grouped into several categories known as data types. Each data type is unique which helps to understand the data better.
4 | ---
5 |
6 | Data types are the classification or categorization of data items. The data items are grouped into several categories known as data types. Each data type is unique, helping to better understand the data.
7 |
8 | ## Python Data Types Overview
9 |
10 | Python has several built-in data types that help us work with different kinds of data. Below are the main categories:
11 |
12 | ### 1. Numeric Types
13 |
14 | #### Integer (`int`)
15 | - Whole numbers without decimal points.
16 | - **Examples**: `-5`, `0`, `100`
17 |
18 | #### Float (`float`)
19 | - Numbers that contain decimal points or are written in scientific notation.
20 | - **Examples**: `3.14`, `0.5`, `-2.7`
21 |
22 | #### Complex (`complex`)
23 | - Numbers with a real and imaginary part.
24 | - **Examples**: `3 + 4j`, `1 - 2j`
25 |
26 | ### 2. Text Type
27 |
28 | #### String (`str`)
29 | - A sequence of characters enclosed within single, double, or triple quotes.
30 | - **Examples**: `'Hello'`, `"Python"`, `'''Multi-line string'''`
31 |
32 | ### 3. Sequence Types
33 |
34 | #### List (`list`)
35 | - A collection of items ordered by position, and they can be of different data types.
36 | - Lists are mutable, meaning you can change, add, or remove items.
37 | - **Examples**: `[1, 2, 3]`, `['apple', 'banana', 'cherry']`
38 |
39 | #### Tuple (`tuple`)
40 | - Similar to lists, but they are immutable, meaning you cannot change them after creation.
41 | - **Examples**: `(1, 2, 3)`, `('apple', 'banana', 'cherry')`
42 |
43 | #### Range (`range`)
44 | - Represents a sequence of numbers, commonly used in loops.
45 | - **Examples**: `range(5)`, `range(1, 10, 2)` (creates numbers from 1 to 9 with a step of 2)
46 |
47 | ### 4. Mapping Type
48 |
49 | #### Dictionary (`dict`)
50 | - A collection of key-value pairs, where each key is unique.
51 | - **Examples**: `{'name': 'John', 'age': 25}`, `{1: 'one', 2: 'two'}`
52 |
53 | ### 5. Set Types
54 |
55 | #### Set (`set`)
56 | - A collection of unique items, unordered, with no duplicates.
57 | - **Examples**: `{1, 2, 3}`, `{'apple', 'banana', 'cherry'}`
58 |
59 | #### Frozen Set (`frozenset`)
60 | - Similar to a set, but immutable.
61 | - **Examples**: `frozenset([1, 2, 3])`, `frozenset({'apple', 'banana'})`
62 |
63 | ### 6. Boolean Type
64 |
65 | #### Boolean (`bool`)
66 | - Represents one of two values: `True` or `False`.
67 | - **Examples**: `True`, `False`
68 |
69 | ### 7. Binary Types
70 |
71 | #### Bytes (`bytes`)
72 | - Immutable sequences of bytes, often used for handling binary data.
73 | - **Examples**: `b'hello'`, `bytes([65, 66, 67])`
74 |
75 | #### Bytearray (`bytearray`)
76 | - A mutable sequence of bytes, used when you need to change data after it has been created.
77 | - **Examples**: `bytearray([65, 66, 67])`
78 |
79 | #### Memoryview (`memoryview`)
80 | - A memory view object allows access to the internal data of an object without copying it.
81 | - **Examples**: `memoryview(b'hello')`
82 |
83 | ## Conclusion
84 |
85 | Understanding data types is essential for programming in Python, as they determine what kind of data you're working with and what operations you can perform on it. By recognizing and using the correct data type, you can write more efficient and error-free code.
86 |
87 |
--------------------------------------------------------------------------------
/src/content/docs/python/innerworking.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Python Inner Working
3 | description: Discussion about Python inner workings
4 | ---
5 |
6 |
7 |
8 | ## Python Bytecode and Virtual Machine
9 | When you run a Python script, the process involves several steps to convert your human-readable code into something that the computer can execute efficiently. Here’s a detailed explanation:
10 |
11 | 
12 |
13 |
14 | 1. **Python Source Code** (`.py` file):
15 | - This is the code you write in a text editor or IDE, saved with a `.py` extension.
16 |
17 | 2. **Compilation to Bytecode**:
18 | - When you run a Python script (e.g., `python guide.py`), Python first compiles the source code into bytecode. This step is mostly hidden from the user.
19 | - **Bytecode**:
20 | - Bytecode is a low-level, platform-independent representation of your source code.
21 | - It is designed to be efficient for execution by the Python Virtual Machine (VM).
22 | - Bytecode files typically have a `.pyc` extension and are stored in a `__pycache__` directory.
23 |
24 | 3. **Python Virtual Machine (VM)**:
25 | - The Python VM is responsible for executing the compiled bytecode.
26 | - The VM interprets the bytecode and performs the necessary operations on the underlying hardware.
27 |
28 | 4. **Benefits of Bytecode**:
29 | - **Platform Independence**: Bytecode can be executed on any platform that has a compatible Python VM.
30 | - **Faster Execution**: Since bytecode is a more compact and efficient representation of your source code, it generally executes faster than interpreting source code directly.
31 |
32 | 5. **Compiled Python Files** (`.pyc` files):
33 | - These files contain the bytecode and are often referred to as frozen binaries.
34 | - They allow Python programs to start faster since the compilation step is skipped.
35 |
36 |
37 |
38 | Happy coding!
39 |
--------------------------------------------------------------------------------
/src/content/docs/python/introduction.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Introduction to Python
3 | description: discussion about Python
4 | ---
5 |
6 | Python is popular programming language known for its simplicity and versatility. It's widely used in web development, data analysis, artificial intelligence, scientific computing and more
7 |
8 | ## Why Python
9 |
10 | - **Easy to Learn** : Python has a clean and readable syntax, making it an excellent choice for beginners.
11 | - **Powerful and Flexible** : Despite its simplicity, Python is very powerful. It supports various programming paradigms, including procedural, object-oriented, and functional programming.
12 | - **Wide Community and Libraries** : Python has Large community and a rich ecosystem of libraries and frameworks, which make it easier to find support and tools for your project
13 |
14 | ## Getting Started
15 |
16 | To start coding in Python, you need to install python on your computer. You can download it from the official [Python website](https://www.python.org/downloads/).
17 |
18 | 
19 |
20 | Its automatically detects your machine and gets you the suitable package for your machine.
21 |
22 | ## Steps to Create and Run "Hello, World!" Program
23 |
24 | ### 1. Open a Text Editor
25 |
26 | You can use any text editor to write your Python code. Some popular choices are:
27 |
28 | - Visual Studio Code
29 | - Sublime Text
30 | - Atom
31 | - Notepad (Windows) / TextEdit (Mac)
32 |
33 | ### 2. Write the Python Code
34 |
35 | Create a new file with a `.py` extension and add the following code:
36 |
37 | ```sh
38 | print("Hello, World!")
39 |
40 | ```
41 |
42 | ### 3. Save the File
43 |
44 | - Save the file with a `.py` extension, for example, `hello_world.py` .
45 |
46 | ### 4. How to Run the Python File
47 |
48 | - Open a Command Line or Terminal.
49 | - Navigate to the File Location.
50 | - Run the Python Program
51 |
52 | Type the following command to run your Python program:
53 |
54 | ```sh
55 | python3 hello_world.py
56 |
57 | ```
58 |
59 | - If you are using Python 3, you might need to use:
60 |
61 | :::note
62 |
63 | ```sh
64 | python3 hello_world.py
65 |
66 | ```
67 |
68 | :::
69 |
70 | If everything is set up correctly, you should see the following output.
71 |
72 | ```python
73 |
74 | Hello, World!
75 |
76 | ```
77 |
78 | ## Print Hero Names in Python
79 |
80 | Here is an example of how you can print hero names in Python:
81 |
82 | ### Write the Python Code
83 |
84 | Create a new file with a `.py` extension and add the following code:
85 |
86 | ```python
87 | def print_hero(hero_name):
88 | print(hero_name)
89 |
90 | print_hero("Hulk")
91 | print_hero("Superman")
92 | print_hero("Spider-Man")
93 |
94 | ```
95 |
96 | ### Save the File
97 |
98 | - Save the file with a `.py` extension, for example, `print_heroes.py`
99 | - Open a Command Line or Terminal.
100 | - Navigate to the File Location.
101 | - Run the Python Program
102 |
103 | Type the following command to run your Python program:
104 |
105 | ```sh
106 | python3 print_heroes.py
107 |
108 | ```
109 |
110 | If everything is set up correctly, you should see the following output.
111 |
112 | ```python
113 |
114 | Hulk
115 | Superman
116 | Spider-Man
117 |
118 |
119 | ```
120 |
--------------------------------------------------------------------------------
/src/content/docs/python/mutable-and-immutable.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Mutable and Immutable Types in Python
3 | description: n Python, understanding the difference between mutable and immutable data types is crucial for efficient and effective programming. This guide will walk you through the concept, implications, and examples of both mutable and immutable objects in Python.n
4 | ---
5 |
6 |
7 |
8 | ## Introduction
9 |
10 | In Python, understanding the difference between mutable and immutable data types is crucial for efficient and effective programming. This guide will walk you through the concept, implications, and examples of both mutable and immutable objects in Python.
11 |
12 | ## Table of Contents
13 |
14 | 1. [What are Mutable and Immutable Objects?](#what-are-mutable-and-immutable-objects)
15 | 2. [Why Does It Matter?](#why-does-it-matter)
16 | 3. [Immutable Data Types](#immutable-data-types)
17 | - [Integers](#integers)
18 | - [Floats](#floats)
19 | - [Strings](#strings)
20 | - [Tuples](#tuples)
21 | 4. [Mutable Data Types](#mutable-data-types)
22 | - [Lists](#lists)
23 | - [Dictionaries](#dictionaries)
24 | - [Sets](#sets)
25 | 5. [Examples and Code Snippets](#examples-and-code-snippets)
26 | 6. [Common Pitfalls and Best Practices](#common-pitfalls-and-best-practices)
27 | 7. [Conclusion](#conclusion)
28 |
29 | ## What are Mutable and Immutable Objects?
30 |
31 | In Python, every variable holds a reference to an object. These objects can either be **mutable** or **immutable**:
32 |
33 | - **Mutable objects** can be changed after they are created.
34 | - **Immutable objects** cannot be changed once they are created.
35 |
36 | ## Why Does It Matter?
37 |
38 | Understanding mutability is important because it affects how variables behave when you manipulate them. When you modify a mutable object, the changes are reflected across all references to that object. On the other hand, modifying an immutable object results in the creation of a new object.
39 |
40 | ## Immutable Data Types
41 |
42 | Immutable data types cannot be modified after their creation. Any operation that tries to modify an immutable object will result in the creation of a new object.
43 |
44 | ### Integers
45 |
46 | Integers are immutable. When you perform an operation on an integer, a new integer is created.
47 |
48 | ```python
49 | x = 10
50 | y = x
51 | x += 5 # x is now 15, y remains 10
52 | ```
53 |
54 | ### Floats
55 |
56 | Floats are also immutable. Similar to integers, operations on floats result in new floats.
57 |
58 | ```python
59 |
60 | a = 3.14
61 | b = a
62 | a += 1.0 # a is now 4.14, b remains 3.14
63 |
64 | ```
65 |
66 | ### Strings
67 |
68 | Strings are immutable. When you try to modify a string, Python creates a new string.
69 |
70 | ```python
71 |
72 | str1 = "hello"
73 | str2 = str1
74 | str1 += " world" # str1 is now "hello world", str2 remains "hello"
75 |
76 | ```
77 |
78 | ### Tuples
79 |
80 | Tuples are immutable. When you try to modify a tuple, Python raises an error.
81 |
82 | ```python
83 | ba = bytearray([1, 2, 3])
84 | ba[0] = 100 # ba is now bytearray(b'd\x02\x03')
85 |
86 | ```
87 |
88 | # Mutable Data Types
89 |
90 | Mutable data types can be modified after their creation. Operations that modify mutable objects change the object itself without creating a new one.
91 |
92 | ### Lists
93 |
94 | Lists are mutable. You can modify a list by adding or removing elements.
95 |
96 | ```python
97 | list1 = [1, 2, 3]
98 | list2 = list1
99 | list1.append(4) # list1 and list2 both become [1, 2, 3, 4]
100 | ```
101 |
102 | ### Dictionaries
103 |
104 | Dictionaries are mutable. You can modify a dictionary by adding or removing key-value pairs.
105 |
106 | ```py
107 | dict1 = {"a": 1, "b": 2}
108 | dict2 = dict1
109 | dict1["c"] = 3 # dict1 and dict2 both become {"a": 1, "b": 2, "c": 3}
110 |
111 | ```
112 |
113 | ### Sets
114 |
115 | Sets are mutable. You can modify a set by adding or removing elements.
116 |
117 | ```py
118 | set1 = {1, 2, 3}
119 | set2 = set1
120 | set1.add(4) # set1 and set2 both become {1, 2, 3, 4}
121 |
122 |
123 | ```
124 |
125 | #Examples and Code Snippets
126 |
127 | ### Example 1: Immutable vs Mutable
128 |
129 | ```py
130 | # Immutable example
131 | a = 5
132 | b = a
133 | a = 10
134 | print(a) # Output: 10
135 | print(b) # Output: 5
136 |
137 | # Mutable example
138 | list1 = [1, 2, 3]
139 | list2 = list1
140 | list1.append(4)
141 | print(list1) # Output: [1, 2, 3, 4]
142 | print(list2) # Output: [1, 2, 3, 4]
143 |
144 | ```
145 |
146 | ### Example 2: Shared References
147 |
148 | ```py
149 | # Immutable
150 | x = "hello"
151 | y = x
152 | x += " world"
153 | print(x) # Output: "hello world"
154 | print(y) # Output: "hello"
155 |
156 | # Mutable
157 | list1 = [1, 2, 3]
158 | list2 = list1
159 | list1[0] = 0
160 | print(list1) # Output: [0, 2, 3]
161 | print(list2) # Output: [0, 2, 3]
162 |
163 | ```
164 |
165 | # Common Pitfalls and Best Practices
166 |
167 | - **Beware of Shared References:**:When working with mutable objects, be careful with shared references as changes to one reference will affect all others.
168 | - **Use Immutable Types for Constants**: a value should not change, prefer immutable types like tuples over lists.
169 | - **Avoid Mutable Default Arguments**: In functions, avoid using mutable objects as default arguments.
170 |
171 | ```py
172 | def func(a, my_list=[]):
173 | my_list.append(a)
174 | return my_list
175 |
176 | print(func(1)) # Output: [1]
177 | print(func(2)) # Output: [1, 2], not [2]
178 | ```
179 |
180 | **Solution:**
181 |
182 | ```py
183 | def func(a, my_list=None):
184 | if my_list is None:
185 | my_list = []
186 | my_list.append(a)
187 | return my_list
188 | ```
189 |
190 | # Further Reading and References
191 |
192 | - [Python Official Documentation: Built-in Types](https://docs.python.org/3/library/stdtypes.html)
193 |
194 | # Conclusion
195 |
196 | Understanding the differences between mutable and immutable types in Python is essential for writing efficient and bug-free code. This guide covered the basics, provided examples, and highlighted common pitfalls. By being mindful of mutability, you can better manage memory, avoid unexpected behavior, and write more predictable programs.
197 |
198 | Happy coding!
199 |
--------------------------------------------------------------------------------
/src/content/docs/python/numbers-in-python.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Numbers in Python
3 | description: Understanding numbers in Python is essential for any programmer. This guide will walk you through the different types of numbers, how they behave, and how to work with them effectively.
4 | ---
5 |
6 |
7 |
8 |
9 | ## Introduction
10 |
11 | Numbers are one of the most fundamental data types in Python. Whether you're adding prices, calculating averages, or working with scientific data, understanding how numbers work is crucial.
12 |
13 | Python makes working with numbers simple and intuitive, but there are a few key concepts to understand to avoid errors and write clean code.
14 |
15 | ---
16 |
17 | ## Types of Numbers in Python
18 |
19 | Python has three main types of numbers:
20 |
21 | 1. **Integers (`int`)** – Whole numbers, positive or negative.
22 | 2. **Floats (`float`)** – Numbers with a decimal point.
23 | 3. **Complex (`complex`)** – Numbers with a real and imaginary part.
24 |
25 | ```python
26 | x = 10 # Integer
27 | y = 3.14 # Float
28 | z = 2 + 3j # Complex
29 | ```
30 |
31 | ---
32 |
33 | ## Basic Arithmetic
34 |
35 | Python can handle basic arithmetic operations just like a calculator:
36 |
37 | ```python
38 | a = 10
39 | b = 3
40 |
41 | # Addition
42 | print(a + b) # 13
43 |
44 | # Subtraction
45 | print(a - b) # 7
46 |
47 | # Multiplication
48 | print(a * b) # 30
49 |
50 | # Division
51 | print(a / b) # 3.3333 (float division)
52 | print(a // b) # 3 (integer division)
53 |
54 | # Modulus (remainder)
55 | print(a % b) # 1
56 |
57 | # Power
58 | print(a ** b) # 1000 (10 to the power of 3)
59 | ```
60 |
61 | ---
62 |
63 | ## Type Conversion
64 |
65 | You can convert between different types of numbers easily:
66 |
67 | ```python
68 | x = 10 # int
69 | y = 3.5 # float
70 |
71 | # Convert int to float
72 | x_float = float(x) # 10.0
73 |
74 | # Convert float to int
75 | y_int = int(y) # 3 (rounds down)
76 |
77 | # String to number
78 | z = "42"
79 | z_int = int(z) # 42
80 | ```
81 |
82 | ---
83 |
84 | ## Common Operations
85 |
86 | Python provides many built-in functions to work with numbers:
87 |
88 | ```python
89 | # Absolute value
90 | print(abs(-7)) # 7
91 |
92 | # Round a number
93 | print(round(3.14159, 2)) # 3.14
94 |
95 | # Max and Min
96 | print(max(5, 10, 15)) # 15
97 | print(min(5, 10, 15)) # 5
98 |
99 | # Sum of a list
100 | print(sum([1, 2, 3, 4])) # 10
101 | ```
102 |
103 | ---
104 |
105 | ## Working with Large Numbers
106 |
107 | Python can handle very large numbers without overflow:
108 |
109 | ```python
110 | big_number = 10 ** 100 # 1 followed by 100 zeros
111 | print(big_number)
112 |
113 | # Scientific notation
114 | sci_number = 3e5 # 3 * 10^5
115 | print(sci_number) # 300000.0
116 | ```
117 |
118 | ---
119 |
120 | ## Best Practices
121 |
122 | - **Use floats carefully** – Floats can sometimes lead to precision errors:
123 | ```python
124 | print(0.1 + 0.2) # 0.30000000000000004
125 | ```
126 | Use `round()` to handle precision issues.
127 | - **Avoid dividing by zero** – Python will raise an error if you divide by zero.
128 | - **Use meaningful variable names** – `price`, `total`, and `quantity` are better than `x`, `y`, `z`.
129 |
130 | ---
131 |
132 | ## Conclusion
133 |
134 | Numbers in Python are powerful and easy to work with. By understanding the basics and following best practices, you can avoid common pitfalls and write more efficient code.
135 |
136 | Happy coding!
137 |
--------------------------------------------------------------------------------
/src/content/docs/python/operators-in-python.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Python Operators and Literal Operators
3 | description: Operators are essential tools in Python that allow you to perform operations on variables and values. This guide explains the different types of operators, including literal operators, with examples to make things clearer.
4 | ---
5 |
6 |
7 |
8 | ## Introduction
9 | In Python, operators are symbols that perform operations on variables and values. They can handle arithmetic, comparisons, and even logical operations.
10 |
11 | Literal operators, on the other hand, help define fixed values directly in the code.
12 |
13 | ---
14 |
15 | ## Types of Operators
16 |
17 | ### 1. Arithmetic Operators
18 | Used for basic math operations.
19 |
20 | ```python
21 | a = 10
22 | b = 3
23 |
24 | print(a + b) # Addition: 13
25 | print(a - b) # Subtraction: 7
26 | print(a * b) # Multiplication: 30
27 | print(a / b) # Division: 3.3333
28 | print(a // b) # Floor Division: 3
29 | print(a % b) # Modulus: 1
30 | print(a ** b) # Exponentiation: 1000
31 | ```
32 |
33 | ---
34 |
35 | ### 2. Comparison Operators
36 | Used to compare two values and return `True` or `False`.
37 |
38 | ```python
39 | x = 5
40 | y = 10
41 |
42 | print(x > y) # False
43 | print(x < y) # True
44 | print(x == y) # False
45 | print(x != y) # True
46 | print(x >= 5) # True
47 | print(y <= 5) # False
48 | ```
49 |
50 | ---
51 |
52 | ### 3. Logical Operators
53 | Combine multiple conditions.
54 |
55 | ```python
56 | x = True
57 | y = False
58 |
59 | print(x and y) # False
60 | print(x or y) # True
61 | print(not x) # False
62 | ```
63 |
64 | ---
65 |
66 | ### 4. Assignment Operators
67 | Used to assign and update variable values.
68 |
69 | ```python
70 | x = 10
71 |
72 | x += 5 # x = x + 5 (x becomes 15)
73 | x -= 2 # x = x - 2 (x becomes 13)
74 | x *= 3 # x = x * 3 (x becomes 39)
75 | x /= 3 # x = x / 3 (x becomes 13.0)
76 | x %= 4 # x = x % 4 (x becomes 1)
77 | ```
78 |
79 | ---
80 |
81 | ### 5. Bitwise Operators
82 | Operate on binary representations of numbers.
83 |
84 | ```python
85 | a = 5 # 0101
86 | b = 3 # 0011
87 |
88 | print(a & b) # AND: 0001 (1)
89 | print(a | b) # OR: 0111 (7)
90 | print(a ^ b) # XOR: 0110 (6)
91 | print(~a) # NOT: 1010 (-6)
92 | print(a << 1) # Left Shift: 1010 (10)
93 | print(b >> 1) # Right Shift: 0001 (1)
94 | ```
95 |
96 | ---
97 |
98 | ### 6. Membership Operators
99 | Check if a value exists in a sequence.
100 |
101 | ```python
102 | list1 = [1, 2, 3, 4]
103 |
104 | print(2 in list1) # True
105 | print(5 not in list1) # True
106 | ```
107 |
108 | ---
109 |
110 | ### 7. Identity Operators
111 | Compare memory locations of two objects.
112 |
113 | ```python
114 | x = [1, 2, 3]
115 | y = x
116 | z = [1, 2, 3]
117 |
118 | print(x is y) # True (same object)
119 | print(x is z) # False (different objects)
120 | print(x == z) # True (same values)
121 | ```
122 |
123 | ---
124 |
125 | ## Literal Operators
126 |
127 | Literal operators help create literal values directly in code.
128 |
129 | ### 1. String Literals
130 | ```python
131 | name = "John" # String literal
132 | greeting = 'Hello, World!'
133 | ```
134 |
135 | ### 2. Numeric Literals
136 | ```python
137 | num = 42 # Integer literal
138 | pi = 3.14 # Float literal
139 | ```
140 |
141 | ### 3. Boolean Literals
142 | ```python
143 | is_active = True
144 | is_deleted = False
145 | ```
146 |
147 | ### 4. List, Tuple, and Dictionary Literals
148 | ```python
149 | my_list = [1, 2, 3] # List literal
150 | my_tuple = (1, 2, 3) # Tuple literal
151 | my_dict = {"name": "Alice", "age": 25} # Dictionary literal
152 | ```
153 |
154 | ### 5. None Literal
155 | Represents the absence of a value.
156 | ```python
157 | x = None
158 | ```
159 |
160 | ---
161 |
162 | ## Operator Precedence
163 | Python follows specific rules to decide the order of operations.
164 |
165 | **Order (Highest to Lowest):**
166 | 1. `**` (Exponentiation)
167 | 2. `*, /, //, %` (Multiplication, Division, Modulus)
168 | 3. `+, -` (Addition, Subtraction)
169 | 4. `==, !=, >, <, >=, <=` (Comparison)
170 | 5. `not`
171 | 6. `and`
172 | 7. `or`
173 |
174 | ```python
175 | result = 5 + 2 * 3 ** 2 # 5 + 2 * 9 -> 5 + 18 -> 23
176 | ```
177 |
178 | ---
179 |
180 | ## Conclusion
181 | Operators are vital in Python programming for performing calculations, comparisons, and more. By mastering operators and literal operators, you'll be able to write more efficient and cleaner code.
182 |
183 | Happy coding!
--------------------------------------------------------------------------------
/src/content/docs/tipsandtools/httpresponsestatuscode.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: HTTP Response Status Codes
3 | description: Discussion about HTTP Response Status Codes
4 | ---
5 |
6 | HTTP response status codes indicate the **successful completion** of a specific HTTP request. Responses are categorized into **five** classes.
7 |
8 | ## Informational responses (100 – 199)
9 |
10 | ### 100 Continue
11 |
12 | This means that the client should continue the request or ignore the response if the request is _already finished_.
13 |
14 | ### 101 Switching Protocols
15 |
16 | This is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.
17 |
18 | ### 102 Processing (WebDAV)
19 |
20 | This indicates that the server has received and is processing the request, but no response is available yet.
21 |
22 | ### 103 Early Hints
23 |
24 | This status code is primarily intended to be used with the Link header. It lets the user agent start preloading resources while the server prepares a response or preconnects to an origin from which the page will need resources.
25 |
26 | ## Successful responses (200 – 299)
27 |
28 | ### 200 OK
29 |
30 | The request was _successful_. The meaning of `success` depends on the HTTP method used:
31 |
32 | - **GET:** The requested resource has been fetched and is included in the message body.
33 | - **HEAD:** Only the representation headers are included in the response without any message body.
34 | - **PUT or POST:** The resource that describes the result of the action is included in the message body.
35 | - **TRACE:** The request message as received by the server is included in the message body.
36 |
37 | ### 201 Created
38 |
39 | The request was _successful_, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.
40 |
41 | ### 202 Accepted
42 |
43 | The request has been received but has not been acted upon yet. This response is noncommittal and is intended for cases where another process or server handles the request, or for batch processing.
44 |
45 | ### 203 Non-Authoritative Information
46 |
47 | This response code indicates that the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the 200 OK response is preferred to this status.
48 |
49 | ### 204 No Content
50 |
51 | There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones.
52 |
53 | ### 205 Reset Content
54 |
55 | This response instructs the user agent to reset the document that sent this request.
56 |
57 | ### 206 Partial Content
58 |
59 | This response code is used when the Range header is sent from the client to request only a part of a resource.
60 |
61 | ### 207 Multi-Status (WebDAV)
62 |
63 | Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
64 |
65 | ### 208 Already Reported (WebDAV)
66 |
67 | Used inside a `` response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
68 |
69 | ### 226 IM Used (HTTP Delta encoding)
70 |
71 | The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
72 |
73 | ## Redirection messages (300 – 399)
74 |
75 | ### 300 Multiple Choices
76 |
77 | The request has multiple possible responses. The user or user agent should choose one. There's no standard way to choose, but using HTML links is recommended for user selection.
78 |
79 | ### 301 Moved Permanently
80 |
81 | The requested resource's URL has been permanently changed. The new URL is provided in the response.
82 |
83 | ### 302 Found
84 |
85 | This response code indicates that the URI of the requested resource has been temporarily changed, and the client should use the same URI for future requests.
86 |
87 | ### 303 See Other
88 |
89 | The server directed the client to retrieve the requested resource from another `URI` using a `GET request`.
90 |
91 | ### 304 Not Modified
92 |
93 | This header is used for caching, informing the client that the response has not been modified, allowing the client to continue using the cached version.
94 |
95 | ### 305 Use Proxy Deprecated
96 |
97 | Previously defined in the HTTP specification, this directive indicated that a requested response must be accessed by a proxy. However, it has been deprecated due to security concerns related to in-band proxy configuration.
98 |
99 | ### 306 unused
100 |
101 | This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification.
102 |
103 | ### 307 Temporary Redirect
104 |
105 | The server sends this response to direct the client to retrieve the requested resource from a different URI using the same method as the prior request. It's similar to the `302 Found` response code, but the user agent must not change the HTTP method used: if a `POST` was used in the first request, a `POST` must be used in the second request.
106 |
107 | ### 308 Permanent Redirect
108 |
109 | When a resource is permanently moved to a new location, as indicated by the `Location:` HTTP Response header, it means that the resource can now be found at the new URI. This is similar to the `301 Moved Permanently` HTTP response code, except that it requires the user agent to use the same HTTP method in the second request as was used in the first request. For example, if the first request used a `POST` method, the second request must also use a POST method.
110 |
111 | ## Client error responses (400 – 499)
112 |
113 | ### 400 Bad Request
114 |
115 | The server can't process the request because of a client error, like bad request syntax or invalid request framing.
116 |
117 | ### 401 Unauthorized
118 |
119 | The client must authenticate itself to get the requested response.
120 |
121 | ### 402 Payment Required (Experimental)
122 |
123 | This code is reserved for future use, mainly for digital payment systems, but it is rarely used.
124 |
125 | ### 403 Forbidden
126 |
127 | The client does not have permission to access the resource, even though the server knows who the client is.
128 |
129 | ### 404 Not Found
130 |
131 | The server can't find the requested resource. It may mean the URL is incorrect, or the resource doesn't exist.
132 |
133 | ### 405 Method Not Allowed
134 |
135 | The request method is not supported by the server for the target resource, like using DELETE on a read-only endpoint.
136 |
137 | ### 406 Not Acceptable
138 |
139 | The server can't find content that matches the criteria provided by the client.
140 |
141 | ### 407 Proxy Authentication Required
142 |
143 | The client must authenticate with a proxy server before the request can be processed.
144 |
145 | ### 408 Request Timeout
146 |
147 | The server timed out waiting for the request. This is often sent by servers to close idle connections.
148 |
149 | ### 409 Conflict
150 |
151 | The request conflicts with the current state of the server.
152 |
153 | ### 410 Gone
154 |
155 | The requested resource has been permanently removed from the server, with no forwarding address.
156 |
157 | ### 411 Length Required
158 |
159 | The server rejected the request because the required Content-Length header is not specified.
160 |
161 | ### 412 Precondition Failed
162 |
163 | The server does not meet one of the preconditions that the client put in its request headers.
164 |
165 | ### 413 Payload Too Large
166 |
167 | The request is larger than the server is willing or able to process.
168 |
169 | ### 414 URI Too Long
170 |
171 | The URI provided in the request is too long for the server to process.
172 |
173 | ### 415 Unsupported Media Type
174 |
175 | The media format of the requested data is not supported by the server.
176 |
177 | ### 416 Range Not Satisfiable
178 |
179 | The server can't provide the requested range of the resource.
180 |
181 | ### 417 Expectation Failed
182 |
183 | The server can't meet the requirements of the Expect request header field.
184 |
185 | ### 418 I'm a teapot
186 |
187 | The server refuses to brew coffee with a teapot.
188 |
189 | ### 421 Misdirected Request
190 |
191 | The request was sent to the wrong server.
192 |
193 | ### 422 Unprocessable Content (WebDAV)
194 |
195 | The server understands the request but can't process the instructions due to semantic errors.
196 |
197 | ### 423 Locked (WebDAV)
198 |
199 | The resource being accessed is locked.
200 |
201 | ### 424 Failed Dependency (WebDAV)
202 |
203 | The request failed because it depended on another request that failed.
204 |
205 | ### 425 Too Early (Experimental)
206 |
207 | The server is not willing to process the request because it might be replayed.
208 |
209 | ### 426 Upgrade Required
210 |
211 | The server refuses to perform the request using the current protocol. The client should switch to a different protocol.
212 |
213 | ### 428 Precondition Required
214 |
215 | The server requires the request to be conditional to prevent conflicts.
216 |
217 | ### 429 Too Many Requests
218 |
219 | The client has sent too many requests in a given amount of time.
220 |
221 | ### 431 Request Header Fields Too Large
222 |
223 | The server won't process the request because its header fields are too large.
224 |
225 | ### 451 Unavailable For Legal Reasons
226 |
227 | The requested resource is unavailable due to legal reasons, such as censorship.
228 |
229 | ## Server error responses (500 – 599)
230 |
231 | ### 500 Internal Server Error
232 |
233 | The server encountered a problem it can't handle.
234 |
235 | ### 501 Not Implemented
236 |
237 | The server doesn't support the request method. Servers must support GET and HEAD methods.
238 |
239 | ### 502 Bad Gateway
240 |
241 | The server, acting as a gateway, got an invalid response.
242 |
243 | ### 503 Service Unavailable
244 |
245 | The server can't handle the request, possibly due to maintenance or overload. This is usually temporary.
246 |
247 | ### 504 Gateway Timeout
248 |
249 | The server, acting as a gateway, didn't get a response in time.
250 |
251 | ### 505 HTTP Version Not Supported
252 |
253 | The server doesn't support the HTTP version used in the request.
254 |
255 | ### 506 Variant Also Negotiates
256 |
257 | The server has a configuration error: the chosen resource is not a proper endpoint for content negotiation.
258 |
259 | ### 507 Insufficient Storage (WebDAV)
260 |
261 | The server can't store the needed data to complete the request.
262 |
263 | ### 508 Loop Detected (WebDAV)
264 |
265 | The server detected an infinite loop while processing the request.
266 |
267 | ### 510 Not Extended
268 |
269 | More extensions are needed for the server to fulfill the request.
270 |
271 | ### 511 Network Authentication Required
272 |
273 | The client needs to authenticate to gain network access.
274 |
--------------------------------------------------------------------------------
/src/content/docs/tipsandtools/regularexpressions.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Regular Expressions in JS
3 | description: Discussion about Regular Expressions in Javascript
4 | ---
5 |
6 | - A regular expression is a sequence of characters that defines a search pattern. It can be used for `string searching` and `manipulation`. JavaScript provides the **RegExp** object for handling regular expressions.
7 |
8 |
9 | ### Basic Syntax
10 |
11 | * **Literal Notation:**
12 |
13 | ```js
14 | /pattern/flags
15 | ```
16 |
17 | * **Constructor Notation:**
18 |
19 | ```js
20 | new RegExp('pattern', 'flags')
21 | ```
22 |
23 | ### Flags
24 |
25 | * `g` : Global search.
26 | * `i` : Case-insensitive search.
27 | * `m` : Multi-line search.
28 | * `u` : Unicode; treat a pattern as a sequence of Unicode code points.
29 | * `y` : Sticky; matches only from the last index.
30 |
31 | **Examples** :
32 |
33 | #### Basic Searching
34 |
35 | ```js
36 | const str = "Hello, World!";
37 | const regex = /Hello/;
38 | console.log(regex.test(str)); // true
39 | ```
40 |
41 | #### Global and Case-Insensitive Search
42 |
43 | ```js
44 | const str = "Hello, hello, HELLO!";
45 | const regex = /hello/gi;
46 | const matches = str.match(regex);
47 | console.log(matches); // ["Hello", "hello", "HELLO"]
48 | ```
49 |
50 | #### Special Characters
51 |
52 | `.` : Any character except newline.
53 |
54 | `\d` : Digit (0-9).
55 |
56 | `\w` : Word character (alphanumeric + underscore).
57 |
58 | `\s` : Whitespace character.
59 |
60 | `\b` : Word boundary.
61 |
62 | `^` : Start of string.
63 |
64 | `$` : End of string.
65 |
66 | `+` : One or more.
67 |
68 | `*` : Zero or more.
69 |
70 | `?` : Zero or one.
71 |
72 | `{n}` : Exactly n occurrences.
73 |
74 | `{n,}` : n or more occurrences.
75 |
76 | `{n,m}` : Between n and m occurrences.
77 |
78 | ```js
79 | const str = "The quick brown fox jumps over 12 lazy dogs.";
80 | const regex = /\b\w{4}\b/g; // Words with exactly 4 letters
81 | const matches = str.match(regex);
82 | console.log(matches); // ["quick", "jumps", "over", "lazy"]
83 | ```
84 |
85 | #### Replacing Substrings
86 |
87 | ```js
88 | const str = "I love JavaScript. JavaScript is awesome!";
89 | const regex = /JavaScript/g;
90 | const newStr = str.replace(regex, "JS");
91 | console.log(newStr); // "I love JS. JS is awesome!"
92 | ```
93 |
94 | #### Extracting Groups
95 |
96 | ```js
97 | const str = "My email is example@example.com.";
98 | const regex = /(\w+)@(\w+)\.(\w+)/;
99 | const matches = str.match(regex);
100 | console.log(matches);
101 | // ["example@example.com", "example", "example", "com"]
102 | // Entire match and groups
103 | ```
104 |
105 | #### Using the `RegExp` Constructor
106 |
107 | ```js
108 | const str = "Hello, World!";
109 | const regex = new RegExp("hello", "i");
110 | console.log(regex.test(str)); // true
111 | ```
112 |
113 | #### Validating Input
114 |
115 | ```js
116 | function validateEmail(email) {
117 | const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
118 | return regex.test(email);
119 | }
120 |
121 | console.log(validateEmail("example@example.com")); // true
122 | console.log(validateEmail("invalid-email")); // false
123 | ```
124 |
125 |
126 |
127 | Regular expressions are powerful tools for text processing. JavaScript's RegExp object provides the flexibility to work with regular expressions in both literal and constructor notations, and with various flags to control the search behavior.
128 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/innerworking.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: TypeScript Inner Working & Installation
3 | description: Discussion about Python inner workings
4 | ---
5 |
6 | To improve the **image placement** and make the README more organized, let’s ensure the image is aligned correctly with relevant content and doesn't interrupt the logical flow. Here’s a refined version with suggestions for better image positioning:
7 |
8 | ---
9 |
10 | # **TypeScript Inner Working**
11 |
12 | **Description**: Discussion about Python inner workings
13 |
14 | > This guide provides a basic understanding of how TypeScript works behind the scenes, starting from writing `.ts` files to their execution in a JavaScript engine like V8.
15 |
16 | ---
17 |
18 | ### 1. **TypeScript Source Code (`.ts` files)**
19 |
20 | - TypeScript is a superset of JavaScript that adds **static typing** and other advanced features.
21 | - Developers write code in **TypeScript files** with the extension `.ts`.
22 | - These files include type annotations, interfaces, and modern JavaScript syntax to improve code quality and reduce runtime errors.
23 |
24 | ---
25 |
26 | ### 2. **Transpiling with `tsc` (TypeScript Compiler)**
27 |
28 | - The TypeScript code cannot run directly in browsers or JavaScript engines. It must be **transpiled** to JavaScript.
29 | - **`tsc` (TypeScript Compiler)** is the tool responsible for converting TypeScript into **JavaScript** files that browsers and Node.js can understand.
30 | - During the transpilation:
31 | - Type annotations are removed.
32 | - TypeScript ensures that type rules are respected, and it flags errors if there are type mismatches.
33 | - The final output is **JavaScript code** in `.js` files.
34 |
35 | ---
36 |
37 | ### 3. **JavaScript Code (`.js` files)**
38 |
39 | - Once the TypeScript code is transpiled, the resulting output is **JavaScript** code, which is identical to what developers write directly in JavaScript.
40 | - The JavaScript code generated can run in **any JavaScript environment**—whether in a browser or on the server using Node.js.
41 |
42 | ---
43 |
44 | ### 4. **Execution by the V8 JavaScript Engine**
45 |
46 | - The final JavaScript code is executed by a **JavaScript engine** like **V8** (used in Google Chrome and Node.js).
47 | - V8 takes the `.js` files, compiles them to machine code, and runs them.
48 | - This ensures that the application behaves exactly as expected, with the added benefit of having caught type-related issues during the development process via TypeScript.
49 |
50 | ---
51 |
52 | ### **Summary Flow**
53 |
54 | 1. **Write**: Code in `.ts` files using TypeScript.
55 | 2. **Transpile**: Use `tsc` to convert TypeScript to JavaScript (`.js`).
56 | 3. **Execute**: Run the JavaScript code using the **V8 JavaScript Engine** (or any other JavaScript runtime).
57 |
58 | ---
59 |
60 | ### **Visual Overview**
61 |
62 | 
63 |
64 | The image above shows the complete workflow from writing TypeScript to executing it in a JavaScript engine.
65 |
66 | ---
67 |
68 | ## **Installation and Setup**
69 |
70 | ---
71 |
72 | ### **Step 1: Install TypeScript**
73 |
74 | You need Node.js installed. Then, install TypeScript globally:
75 |
76 | ```bash
77 | npm install -g typescript
78 | ```
79 |
80 | ### **Step 2: Verify Installation**
81 |
82 | Check if TypeScript is installed:
83 |
84 | ```bash
85 | tsc --version
86 | ```
87 |
88 | ### **Step 3: Create Your First TypeScript File**
89 |
90 | Create a file named `index.ts` with the following code:
91 |
92 | ```ts
93 | let greeting: string = "Hello, TypeScript!";
94 | console.log(greeting);
95 | ```
96 |
97 | ### **Step 4: Compile the TypeScript Code**
98 |
99 | Transpile the TypeScript file to JavaScript:
100 |
101 | ```bash
102 | tsc index.ts
103 | ```
104 |
105 | This will generate an `index.js` file with the compiled JavaScript code.
106 |
107 | ### **Step 5: Run the JavaScript Code**
108 |
109 | Execute the compiled JavaScript file:
110 |
111 | ```bash
112 | node index.js
113 | ```
114 |
115 | ---
116 |
117 | ## **Resources for Learning More**
118 |
119 | - [TypeScript Documentation](https://www.typescriptlang.org/docs/)
120 | - [TypeScript Playground](https://www.typescriptlang.org/play)
121 |
122 | ---
123 |
124 | ## **Conclusion**
125 |
126 | TypeScript improves JavaScript development with static typing, better tooling, and maintainable code. It’s easy to get started and can significantly reduce bugs in your applications.
127 |
128 | Happy coding! 🎉
129 |
130 | ---
131 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-classes.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Classes in TypeScript
3 | description: Welcome! In this guide, we’ll learn how to use classes in TypeScript. Classes help you create objects with similar properties and functions. Let’s get started!
4 | ---
5 |
6 | Welcome! In this guide, we’ll learn how to use classes in TypeScript. Classes help you create objects with similar properties and functions. Let’s get started!
7 |
8 |
9 | ## What Are Classes?
10 |
11 | Classes are like blueprints for creating objects. They group together data (like a person's name or age) and actions (like saying hello). Using classes makes your code neat and easier to understand.
12 |
13 | ## How to Create a Class
14 |
15 | To create a class, you use the `class` keyword followed by the name of your class. Here’s a simple example:
16 |
17 | ```typescript
18 | class Person {
19 | name: string;
20 | age: number;
21 |
22 | constructor(name: string, age: number) {
23 | this.name = name;
24 | this.age = age;
25 | }
26 |
27 | greet(): string {
28 | return `Hello, my name is ${this.name} and I'm ${this.age} years old.`;
29 | }
30 | }
31 |
32 | const person = new Person("Saurabh", 18);
33 | console.log(person.greet()); // Output: Hello, my name is Saurabh and I'm 18 years old.
34 | ```
35 |
36 | ### What’s Happening Here?
37 |
38 | - **Properties**: These are like variables inside the class (e.g., `name` and `age`).
39 | - **Constructor**: This is a special function that runs when you create a new object. It sets up the properties.
40 | - **Methods**: These are functions that belong to the class (e.g., `greet()`).
41 |
42 | ## Inheritance
43 |
44 | Inheritance lets one class use properties and methods from another class. This saves you time and helps avoid repeating code.
45 |
46 | ```typescript
47 | class Employee extends Person {
48 | position: string;
49 |
50 | constructor(name: string, age: number, position: string) {
51 | super(name, age); // Calls the constructor of the Person class
52 | this.position = position;
53 | }
54 |
55 | describe(): string {
56 | return `I work as a ${this.position}.`;
57 | }
58 | }
59 |
60 | const employee = new Employee("Yogita", 28, "Developer");
61 | console.log(employee.greet()); // Output: Hello, my name is Yogita and I'm 28 years old.
62 | console.log(employee.describe()); // Output: I work as a Developer.
63 | ```
64 |
65 | ## Access Modifiers
66 |
67 | Access modifiers help control who can see or change certain parts of your class.
68 |
69 | - **public**: Everyone can access it (default).
70 | - **private**: Only the class can access it.
71 | - **protected**: Only the class and its children can access it.
72 |
73 | ```typescript
74 | class Car {
75 | public brand: string;
76 | private model: string;
77 | protected year: number;
78 |
79 | constructor(brand: string, model: string, year: number) {
80 | this.brand = brand;
81 | this.model = model;
82 | this.year = year;
83 | }
84 |
85 | public getModel(): string {
86 | return this.model; // Allows access to the private model
87 | }
88 | }
89 |
90 | const car = new Car("Toyota", "Camry", 2020);
91 | console.log(car.brand); // Output: Toyota
92 | // console.log(car.model); // Error: Property 'model' is private
93 | console.log(car.getModel()); // Output: Camry
94 | ```
95 |
96 | ## Readonly Properties
97 |
98 | The `readonly` modifier allows you to create properties that can only be set once, either at the time of declaration or within the constructor. This ensures that these properties cannot be modified later, promoting immutability.
99 |
100 | ```typescript
101 | class Book {
102 | readonly title: string;
103 | readonly author: string;
104 |
105 | constructor(title: string, author: string) {
106 | this.title = title;
107 | this.author = author;
108 | }
109 | }
110 |
111 | const book = new Book("1984", "George Orwell");
112 | console.log(book.title); // Output: 1984
113 | // book.title = "Animal Farm"; // Error: Cannot assign to 'title' because it is a read-only property
114 | ```
115 |
116 | ## Getters and Setters
117 |
118 | Getters and setters let you control how properties are accessed and updated. They help keep your data safe.
119 |
120 | ```typescript
121 | class Circle {
122 | private _radius: number;
123 |
124 | constructor(radius: number) {
125 | this._radius = radius;
126 | }
127 |
128 | get radius(): number {
129 | return this._radius; // Gets the radius
130 | }
131 |
132 | set radius(value: number) {
133 | if (value > 0) {
134 | this._radius = value; // Sets a new radius if it's positive
135 | }
136 | }
137 | }
138 |
139 | const circle = new Circle(5);
140 | console.log(circle.radius); // Output: 5
141 | circle.radius = 10;
142 | console.log(circle.radius); // Output: 10
143 | ```
144 |
145 | ### Key Points :
146 |
147 | - **Organization**: Classes help you keep your code organized.
148 | - **Reuse**: Inheritance allows you to use code from other classes.
149 | - **Control**: Access modifiers help you manage who can see or change your data.
150 | - **Immutability**: `readonly` properties ensure certain data remains unchanged after initialization.
151 |
152 | ### 💡 **Conclusion**
153 |
154 | Classes are a great way to organize your code in TypeScript. They let you build complex objects while keeping everything clear and manageable.
155 |
156 | Happy coding with TypeScript! 🎉
157 |
158 | ---
159 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-data-types.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: 📘 TypeScript Data Types
3 | description: Welcome to this short guide! TypeScript adds types to JavaScript, making your code safer and easier to manage. Below are the essential data types in TypeScript, with simple explanations. 🚀
4 | ---
5 |
6 |
7 | Welcome to this short guide! TypeScript adds types to JavaScript, making your code safer and easier to manage. Below are the essential data types in TypeScript, with simple explanations. 🚀
8 |
9 | ---
10 |
11 | ### ⚡️ 1. **Number**
12 |
13 | - **Example:** `let age: number = 25;`
14 | - Numbers include integers and decimals (e.g., `10`, `3.14`).
15 |
16 | ---
17 |
18 | ### ⚡️ 2. **String**
19 |
20 | - **Example:** `let name: string = "Saurabh";`
21 | - Represents text (always enclosed in quotes).
22 |
23 | ---
24 |
25 | ### ⚡️ 3. **Boolean**
26 |
27 | - **Example:** `let isActive: boolean = true;`
28 | - Holds either `true` or `false` values.
29 |
30 | ---
31 |
32 | ### ⚡️ 4. **BigInt**
33 |
34 | - **Example:** `let bigNum: bigint = 9007199254740991n;`
35 | - Used for very large numbers beyond `Number` limits. Add `n` at the end.
36 |
37 | ---
38 |
39 | ### ⚡️ 5. **Array**
40 |
41 | - **Example:** `let numbers: number[] = [1, 2, 3];`
42 | - Holds a list of values of the same type.
43 |
44 | ---
45 |
46 | ### ⚡️ 6. **Tuple**
47 |
48 | - **Example:** `let person: [string, number] = ["Alice", 30];`
49 | - Fixed-size arrays with known types for each element.
50 |
51 | ---
52 |
53 | ### ⚡️ 7. **Any**
54 |
55 | - **Example:** `let data: any = "Hello";`
56 | - Can store **any type**. Use carefully!
57 |
58 | ---
59 |
60 | ### ⚡️ 8. **Unknown**
61 |
62 | - **Example:** `let input: unknown = 42;`
63 | - Similar to `any`, but safer. Requires type checking before use.
64 |
65 | ---
66 |
67 | ### ⚡️ 9. **Void**
68 |
69 | - **Example:**
70 |
71 | ```ts
72 | function logMessage(): void {
73 | console.log("Hello");
74 | }
75 | ```
76 |
77 | - No value is returned (used in functions).
78 |
79 | ---
80 |
81 | ### ⚡️ 10. **Never**
82 |
83 | - **Example:**
84 |
85 | ```ts
86 | function error(): never {
87 | throw new Error("Something went wrong");
88 | }
89 | ```
90 |
91 | - Represents functions that never return (e.g., errors).
92 |
93 | ---
94 |
95 | ### ⚡️ 11. **Enum**
96 |
97 | - **Example:**
98 |
99 | ```ts
100 | enum Direction {
101 | Up = 1,
102 | Down,
103 | Left,
104 | Right,
105 | }
106 | let move: Direction = Direction.Up;
107 | ```
108 |
109 | - A way to define named constants.
110 |
111 | ---
112 |
113 | That’s it! TypeScript’s types help you write reliable, error-free code. Happy coding! 🎉
114 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-decorators.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Decorators in TypeScript"
3 | description: Decorators are special functions that allow you to modify classes, methods, properties, or parameters. They help add extra functionality in a clean and reusable way, often used in frameworks like Angular.
4 | ---
5 |
6 | Decorators are special functions that allow you to modify classes, methods, properties, or parameters. They help add extra functionality in a clean and reusable way, often used in frameworks like Angular.
7 |
8 | ---
9 |
10 | ## Enabling Decorators
11 |
12 | First, you need to enable decorators in your `tsconfig.json`:
13 |
14 | ```json
15 | {
16 | "compilerOptions": {
17 | "experimentalDecorators": true
18 | }
19 | }
20 | ```
21 |
22 | ---
23 |
24 | ## Types of Decorators
25 |
26 | ### 1. **Class Decorator**
27 |
28 | Used to modify or enhance a class.
29 |
30 | ```typescript
31 | function Logger(constructor: Function) {
32 | console.log(`Class created: ${constructor.name}`);
33 | }
34 |
35 | @Logger
36 | class Person {
37 | constructor(public name: string) {}
38 | }
39 | ```
40 |
41 | When the class is created, the decorator logs the class name.
42 |
43 | ---
44 |
45 | ### 2. **Method Decorator**
46 |
47 | Used to modify a method's behavior.
48 |
49 | ```typescript
50 | function MeasureTime(target: any, key: string, descriptor: PropertyDescriptor) {
51 | const original = descriptor.value;
52 | descriptor.value = function (...args: any[]) {
53 | console.time(key);
54 | const result = original.apply(this, args);
55 | console.timeEnd(key);
56 | return result;
57 | };
58 | }
59 |
60 | class MathOperations {
61 | @MeasureTime
62 | add(a: number, b: number): number {
63 | return a + b;
64 | }
65 | }
66 |
67 | const math = new MathOperations();
68 | math.add(2, 3); // Logs the time taken for the 'add' method.
69 | ```
70 |
71 | ---
72 |
73 | ### 3. **Property Decorator**
74 |
75 | Used to observe or modify a property.
76 |
77 | ```typescript
78 | function ReadOnly(target: any, key: string) {
79 | Object.defineProperty(target, key, {
80 | writable: false,
81 | });
82 | }
83 |
84 | class Car {
85 | @ReadOnly
86 | brand = "Toyota";
87 | }
88 |
89 | const car = new Car();
90 | car.brand = "Honda"; // Error: Cannot assign to read-only property.
91 | ```
92 |
93 | ---
94 |
95 | ### 4. **Parameter Decorator**
96 |
97 | Used to inspect or modify parameters.
98 |
99 | ```typescript
100 | function LogParam(target: any, key: string, index: number) {
101 | console.log(`Parameter ${index} in ${key} was decorated.`);
102 | }
103 |
104 | class User {
105 | greet(@LogParam message: string) {
106 | console.log(message);
107 | }
108 | }
109 |
110 | new User().greet("Hello"); // Logs: "Parameter 0 in greet was decorated."
111 | ```
112 |
113 | ---
114 |
115 | ### Key Points :
116 |
117 | - Decorators can modify classes, methods, properties, and parameters.
118 | - They are useful for logging, access control, and more.
119 | - Decorators don’t change the logic but wrap it with extra functionality.
120 |
121 | ---
122 |
123 | ### 💡 **Conclusion**
124 |
125 | Decorators make code cleaner by separating concerns. Use them to enhance logic without cluttering core code.
126 |
127 | Happy coding with **TypeScript**! 🎉
128 |
129 | ##
130 | ---
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-functions.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Functions in TypeScript
3 | description: Welcome! This guide will help you understand how to create and use functions in TypeScript. Functions are essential for writing organized and reusable code. Let’s break it down step by step!
4 | ---
5 |
6 | Welcome! This guide will help you understand how to create and use functions in TypeScript. Functions are essential for writing organized and reusable code. Let’s break it down step by step!
7 |
8 | ## What Are Functions ?
9 |
10 | Functions are blocks of code designed to perform a specific task. You can think of them as little machines that take inputs, do something with them, and give you an output. In TypeScript, you can define functions with specific types, which helps catch errors early and makes your code clearer.
11 |
12 | ## How to Define Functions
13 |
14 | There are several ways to define functions in TypeScript:
15 |
16 | ### 1. Function Declarations
17 |
18 | This is the most straightforward way to define a function. You give it a name and specify what it does.
19 |
20 | ```typescript
21 | function greet(name: string): string {
22 | return `Hello, ${name}!`;
23 | }
24 |
25 | console.log(greet("TypeScript")); // Output: Hello, TypeScript!
26 | ```
27 |
28 | ### 2. Function Expressions
29 |
30 | With function expressions, you create a function and assign it to a variable. This is useful for storing functions for later use.
31 |
32 | ```typescript
33 | const add = function (x: number, y: number): number {
34 | return x + y;
35 | };
36 |
37 | console.log(add(5, 3)); // Output: 8
38 | ```
39 |
40 | ### 3. Arrow Functions
41 |
42 | Arrow functions are a more concise way to write function expressions. They’re especially handy for shorter functions.
43 |
44 | ```typescript
45 | const multiply = (x: number, y: number): number => x * y;
46 |
47 | console.log(multiply(4, 2)); // Output: 8
48 | ```
49 |
50 | ## Optional and Default Parameters
51 |
52 | Sometimes, you might want to make a parameter optional or set a default value. Here’s how you can do that:
53 |
54 | ### Optional Parameters
55 |
56 | Add a `?` after the parameter name to make it optional.
57 |
58 | ```typescript
59 | function greetWithDefault(name: string, greeting?: string): string {
60 | return `${greeting || "Hello"}, ${name}!`;
61 | }
62 |
63 | console.log(greetWithDefault("TypeScript")); // Output: Hello, TypeScript!
64 | ```
65 |
66 | ### Default Parameters
67 |
68 | You can set a default value for a parameter if it’s not provided.
69 |
70 | ```typescript
71 | function greetWithDefault(name: string, greeting: string = "Hello"): string {
72 | return `${greeting}, ${name}!`;
73 | }
74 |
75 | console.log(greetWithDefault("TypeScript")); // Output: Hello, TypeScript!
76 | console.log(greetWithDefault("TypeScript", "Welcome")); // Output: Welcome, TypeScript!
77 | ```
78 |
79 | ## Rest Parameters
80 |
81 | Rest parameters let you accept an indefinite number of arguments. This is useful when you don’t know how many inputs you’ll get.
82 |
83 | ```typescript
84 | function sum(...numbers: number[]): number {
85 | return numbers.reduce((total, num) => total + num, 0);
86 | }
87 |
88 | console.log(sum(1, 2, 3, 4)); // Output: 10
89 | ```
90 |
91 | ### Key Points :
92 |
93 | - **Type Safety**: Specify types for function parameters and return values to catch errors early.
94 | - **Flexibility**: Use optional, default, and rest parameters to create versatile functions.
95 | - **Code Clarity**: Clear function definitions improve readability and make your code easier to maintain.
96 |
97 | ### 💡 **Conclusion**
98 |
99 | Functions are a powerful feature in TypeScript that help you organize your code effectively. By using typed parameters and return types, you can create safer and more reliable applications.
100 |
101 | Happy coding with TypeScript! 🎉
102 |
103 | ---
104 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-generics.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Generics in TypeScript
3 | description: Welcome! In this guide, we’ll explore generics in TypeScript. Generics provide a way to create reusable components and functions that work with any data type while maintaining type safety. Let’s dive in!
4 | ---
5 |
6 | ## What Are Generics?
7 |
8 | Generics allow you to define functions, classes, and interfaces that can work with any type of data without losing the information about the type. This leads to more flexible and reusable code.
9 |
10 | ## Why Use Generics?
11 |
12 | - **Type Safety**: Generics help catch type errors at compile time instead of runtime.
13 | - **Reusability**: You can create a single function or class that works with different types.
14 | - **Clarity**: Generics make your code easier to understand by explicitly stating the types.
15 |
16 | ## How to Use Generics
17 |
18 | ### Generic Functions
19 |
20 | You can create a function that takes a type parameter by using angle brackets (``) to define the type. Here’s an example of a generic function:
21 |
22 | ```typescript
23 | function identity(arg: T): T {
24 | return arg;
25 | }
26 |
27 | const result1 = identity("Hello, Generics!");
28 | console.log(result1); // Output: Hello, Generics!
29 |
30 | const result2 = identity(42);
31 | console.log(result2); // Output: 42
32 | ```
33 |
34 | ### Generic Interfaces
35 |
36 | You can also use generics in interfaces to define the structure of objects that can work with any type.
37 |
38 | ```typescript
39 | interface Box {
40 | contents: T;
41 | }
42 |
43 | const stringBox: Box = { contents: "This is a string box." };
44 | const numberBox: Box = { contents: 123 };
45 | console.log(stringBox.contents); // Output: This is a string box.
46 | console.log(numberBox.contents); // Output: 123
47 | ```
48 |
49 | ### Generic Classes
50 |
51 | You can create classes that work with generic types, allowing you to create instances with different data types.
52 |
53 | ```typescript
54 | class Container {
55 | private items: T[] = [];
56 |
57 | addItem(item: T): void {
58 | this.items.push(item);
59 | }
60 |
61 | getItems(): T[] {
62 | return this.items;
63 | }
64 | }
65 |
66 | const stringContainer = new Container();
67 | stringContainer.addItem("Item 1");
68 | stringContainer.addItem("Item 2");
69 | console.log(stringContainer.getItems()); // Output: ["Item 1", "Item 2"]
70 |
71 | const numberContainer = new Container();
72 | numberContainer.addItem(1);
73 | numberContainer.addItem(2);
74 | console.log(numberContainer.getItems()); // Output: [1, 2]
75 | ```
76 |
77 | ## Constraints
78 |
79 | Sometimes, you may want to restrict the types that can be used with generics. You can do this by adding constraints. For example, you can specify that a type must extend a certain interface:
80 |
81 | ```typescript
82 | interface HasLength {
83 | length: number;
84 | }
85 |
86 | function logLength(arg: T): void {
87 | console.log(`Length: ${arg.length}`);
88 | }
89 |
90 | logLength("Hello, Generics!"); // Output: Length: 16
91 | logLength([1, 2, 3]); // Output: Length: 3
92 | // logLength(123); // Error: Argument of type 'number' is not assignable to parameter of type 'HasLength'.
93 | ```
94 |
95 | ### Key Point :
96 |
97 | - **Generics**: Allow you to create flexible and reusable components.
98 | - **Type Safety**: Catch errors at compile time.
99 | - **Constraints**: Restrict types to ensure they meet certain criteria.
100 |
101 | ### 💡 **Conclusion**
102 |
103 | Generics are a powerful feature in TypeScript that enable you to write code that is both flexible and type-safe. By using generics, you can create functions, classes, and interfaces that work with a variety of types while maintaining clarity and organization.
104 |
105 | Happy coding with TypeScript! 🎉
106 |
107 | ---
108 |
109 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-index-signatures.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Index Signatures in TypeScript"
3 | description: "In TypeScript, index signatures let you define objects with dynamic keys. These are useful when the property names are not known befor ehand, but the value types are predictable."
4 | ---
5 |
6 | In TypeScript, **index signatures** let you define objects with dynamic keys. These are useful when the property names are not known beforehand, but the value types are predictable.
7 |
8 | ---
9 |
10 | ## Basic Example
11 |
12 | ```typescript
13 | interface UserRoles {
14 | [role: string]: string;
15 | }
16 |
17 | const roles: UserRoles = {
18 | admin: "Admin",
19 | user: "User",
20 | };
21 |
22 | console.log(roles.admin); // Output: Admin
23 | ```
24 |
25 | Here, any string key can be added, and its value must be a string.
26 |
27 | ---
28 |
29 | ## Number Index Example
30 |
31 | ```typescript
32 | interface Scores {
33 | [index: number]: number;
34 | }
35 |
36 | const studentScores: Scores = [85, 90, 78];
37 |
38 | console.log(studentScores[1]); // Output: 90
39 | ```
40 |
41 | This allows you to define an array where each index holds a number value.
42 |
43 | ---
44 |
45 | ### 💡 **Conclusion**
46 | Index signatures are handy when working with objects or arrays with flexible keys. They help maintain type safety while giving you the freedom to add dynamic properties or indexes. Use them when you need predictable value types but variable keys.
47 |
48 | ---
49 |
50 |
51 | Happy coding with **Typescript**! 🎉
52 |
53 |
54 |
55 | ---
56 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-literal-types.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Literal Types in TypeScript"
3 | description: "n TypeScript, optional properties are fields in an object that you can include or leave out. If a property is optional, you can create objects without that property."
4 | ---
5 |
6 | Welcome! This guide will explain **Literal Types** in TypeScript. They are a powerful way to make your code more predictable by narrowing down what values a variable can hold. Let’s walk through how they work.
7 |
8 | ## What Are Literal Types?
9 |
10 | Literal types let you specify an exact value for a variable, rather than just a general type like `string` or `number`. Think of it like saying: _“This variable can only be one specific thing.”_
11 |
12 | ### Example of Literal Types:
13 |
14 | ```typescript
15 | let direction: "up" | "down" | "left" | "right";
16 |
17 | direction = "up"; // ✅ This works
18 | direction = "sideways"; // ❌ Error: "sideways" is not assignable
19 | ```
20 |
21 | Here, `direction` can only have one of four literal values: `"up"`, `"down"`, `"left"`, or `"right"`.
22 |
23 | ---
24 |
25 | ## Using Literal Types
26 |
27 | Literal types work great for defining valid values more precisely. Let's see where they can be useful.
28 |
29 | ### 1. String Literals
30 |
31 | ```typescript
32 | type Role = "admin" | "user" | "guest";
33 |
34 | let myRole: Role = "admin"; // ✅ Valid
35 | myRole = "superuser"; // ❌ Error: "superuser" isn't part of the Role type
36 | ```
37 |
38 | This ensures that `myRole` will always have one of the allowed values.
39 |
40 | ### 2. Number Literals
41 |
42 | ```typescript
43 | let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
44 |
45 | diceRoll = 3; // ✅ Valid
46 | diceRoll = 7; // ❌ Error: 7 is not allowed
47 | ```
48 |
49 | This way, the value for `diceRoll` will always represent a valid dice roll.
50 |
51 | ---
52 |
53 | ## Literal Types with Functions
54 |
55 | You can use literal types with functions to ensure only certain inputs are accepted.
56 |
57 | ```typescript
58 | function respond(status: "success" | "error"): string {
59 | return `Response status: ${status}`;
60 | }
61 |
62 | console.log(respond("success")); // ✅ Output: Response status: success
63 | console.log(respond("pending")); // ❌ Error: "pending" is not a valid status
64 | ```
65 |
66 | Here, the `respond` function only accepts `"success"` or `"error"` as arguments.
67 |
68 | ---
69 |
70 | ## Combining Literals with Types
71 |
72 | You can use literal types with other types to build more useful structures.
73 |
74 | ### Example with Objects:
75 |
76 | ```typescript
77 | type Button = {
78 | label: string;
79 | color: "blue" | "green" | "red";
80 | };
81 |
82 | const submitButton: Button = {
83 | label: "Submit",
84 | color: "blue",
85 | };
86 |
87 | console.log(submitButton); // ✅ Output: { label: 'Submit', color: 'blue' }
88 | ```
89 |
90 | This ensures that the `color` of a button can only be `"blue"`, `"green"`, or `"red"`.
91 |
92 | ---
93 |
94 | ## Literal Types with `const`
95 |
96 | When you declare a variable with `const`, TypeScript automatically assigns it a literal type. This helps keep things predictable.
97 |
98 | ```typescript
99 | const pi = 3.14; // pi's type is 3.14 (literal type), not just "number"
100 |
101 | let radius: number = 10;
102 | let area = pi * radius * radius; // Works fine
103 | ```
104 |
105 | ---
106 |
107 | ### Key Points :
108 |
109 | - **Exact Values**: Literal types allow only specific values for variables.
110 | - **Predictable Code**: They help prevent invalid inputs and reduce bugs.
111 | - **Flexible**: You can combine literal types with other types like objects or unions.
112 |
113 | ### 💡 **Conclusion**
114 |
115 | Literal types in TypeScript help you narrow down the range of valid values for variables and functions, making your code safer and more predictable. Use them whenever you need strict control over your data!
116 |
117 | Happy coding with TypeScript! 🎉
118 |
119 | ---
120 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-modules.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Modules in TypeScript"
3 | description: Modules help you split your code into smaller, reusable parts, making it easier to manage. Each module can export variables, functions, or classes to be used in other files.
4 | ---
5 |
6 |
7 | Modules help you split your code into smaller, reusable parts, making it easier to manage. Each module can export variables, functions, or classes to be used in other files.
8 |
9 | ---
10 |
11 | ## Exporting from a Module
12 |
13 | ### Named Exports
14 | You can export multiple things from a module:
15 |
16 | ```typescript
17 | // math.ts
18 | export const add = (a: number, b: number) => a + b;
19 | export const subtract = (a: number, b: number) => a - b;
20 | ```
21 |
22 | Importing named exports:
23 |
24 | ```typescript
25 | // app.ts
26 | import { add, subtract } from './math';
27 |
28 | console.log(add(5, 3)); // 8
29 | console.log(subtract(10, 4)); // 6
30 | ```
31 |
32 | ---
33 |
34 | ### Default Exports
35 | A module can have one default export:
36 |
37 | ```typescript
38 | // greet.ts
39 | export default (name: string) => `Hello, ${name}!`;
40 | ```
41 |
42 | Importing a default export:
43 |
44 | ```typescript
45 | // app.ts
46 | import greet from './greet';
47 |
48 | console.log(greet('TypeScript')); // Hello, TypeScript!
49 | ```
50 |
51 | ---
52 |
53 | ## Importing Everything
54 |
55 | You can import everything from a module as an object:
56 |
57 | ```typescript
58 | // app.ts
59 | import * as Math from './math';
60 |
61 | console.log(Math.add(2, 3)); // 5
62 | ```
63 |
64 | ---
65 |
66 | ### Key Points :
67 | - **Named exports** allow exporting multiple things.
68 | - **Default exports** export one value per module.
69 | - Use `import *` to import all exports as an object.
70 |
71 | ---
72 |
73 | ### 💡 **Conclusion**
74 |
75 | Modules help keep your code organized and reusable. Use them to split logic into smaller parts and import what you need!
76 |
77 |
78 |
79 | ---
80 |
81 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-namespaces.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Namespaces in TypeScript
3 | description: Namespaces in TypeScript are a way to organize code into logical units, helping avoid name collisions in large codebases by grouping related functions, classes, or interfaces under a single namespace. Think of them as containers for related functionality.
4 | ---
5 |
6 | Namespaces in TypeScript help **organize code** into logical groups. They also **avoid name conflicts** by grouping related functions, classes, or variables under a single namespace. Think of them like folders that keep your code neat and structured.
7 |
8 | ---
9 |
10 | ## Creating a Namespace
11 |
12 | You can create a namespace with the `namespace` keyword.
13 |
14 | ```typescript
15 | namespace Utilities {
16 | export function logMessage(message: string): void {
17 | console.log(`Log: ${message}`);
18 | }
19 |
20 | export const version = "1.0.0";
21 | }
22 | ```
23 |
24 | - **`export`**: Only items marked with `export` are available outside the namespace.
25 |
26 | ---
27 |
28 | ## Using a Namespace
29 |
30 | To access things inside a namespace, you prefix them with the namespace name.
31 |
32 | ```typescript
33 | Utilities.logMessage("Hello from Utilities!"); // ✅ Works
34 | console.log(Utilities.version); // ✅ Output: 1.0.0
35 | ```
36 |
37 | ---
38 |
39 | ## Nested Namespaces
40 |
41 | You can **nest namespaces** to group related code even further.
42 |
43 | ```typescript
44 | namespace App {
45 | export namespace User {
46 | export function getUserInfo(id: number) {
47 | return `User ID: ${id}`;
48 | }
49 | }
50 | }
51 |
52 | console.log(App.User.getUserInfo(42)); // ✅ Output: User ID: 42
53 | ```
54 |
55 | ---
56 |
57 | ## When to Use Namespaces vs. Modules
58 |
59 | - **Use namespaces** when your code is in the same project or file.
60 | - **Use ES Modules** (`import`/`export`) for code that spans multiple files or needs to be shared with others.
61 |
62 | > In modern TypeScript, ES Modules are often preferred for better compatibility.
63 |
64 | ---
65 |
66 | ## Aliasing a Namespace
67 |
68 | You can create **shorter aliases** for long namespaces to make your code cleaner.
69 |
70 | ```typescript
71 | namespace App.Utilities {
72 | export function printDate() {
73 | console.log(new Date());
74 | }
75 | }
76 |
77 | import Utils = App.Utilities;
78 | Utils.printDate(); // ✅ Output: Current date and time
79 | ```
80 |
81 | ---
82 |
83 | ### Key Takeaways
84 |
85 | - **Organized Code**: Namespaces group related code together.
86 | - **No Conflicts**: They prevent name clashes between variables or functions.
87 | - **Exporting Matters**: Use `export` to make items accessible outside the namespace.
88 | - **Prefer Modules**: For larger projects, **ES Modules** are more suitable.
89 |
90 | ---
91 |
92 | ## 💡 Conclusion
93 |
94 | Namespaces in TypeScript help structure your code and keep things organized. They are great for internal projects, but when working with larger or multi-file setups, consider using **ES Modules** instead.
95 |
96 | Happy coding with **Typescript**! 🎉
97 |
98 |
99 |
100 | ---
101 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-optional-properties.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "TypeScript Optional Properties"
3 | description: "n TypeScript, optional properties are fields in an object that you can include or leave out. If a property is optional, you can create objects without that property."
4 | ---
5 |
6 | ## What Are Optional Properties?
7 |
8 | In TypeScript, optional properties are fields in an object that you can include or leave out. If a property is optional, you can create objects without that property.
9 |
10 | ## How to Define Optional Properties
11 |
12 | To make a property optional, add a `?` after the property name in your type definition.
13 |
14 | ### Example :
15 |
16 | ```typescript
17 | type Address = {
18 | street: string; // Required
19 | city?: string; // Optional
20 | postalCode?: string; // Optional
21 | };
22 |
23 | // Full address with all properties
24 | let fullAddress: Address = {
25 | street: "123 Main St",
26 | city: "New York",
27 | postalCode: "10001",
28 | };
29 |
30 | // Partial address without optional properties
31 | let partialAddress: Address = {
32 | street: "456 Park Ave",
33 | };
34 |
35 | // Logging the addresses
36 | console.log(fullAddress); // { street: '123 Main St', city: 'New York', postalCode: '10001' }
37 | console.log(partialAddress); // { street: '456 Park Ave' }
38 | ```
39 |
40 | ### Key Points :
41 |
42 | - **Required vs. Optional**: In the `Address` type, `street` is required, while `city` and `postalCode` are optional.
43 | - **Flexibility**: You can create objects with just the required properties or include any combination of optional ones.
44 |
45 | ## 💡 Conclusion
46 |
47 | Using optional properties makes your TypeScript code more flexible and adaptable. This way, you can handle different data scenarios easily.
48 |
49 | Happy coding with **TypeScript**! 🎉
50 |
51 | ---
52 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-type-and-interfaces.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: TypeScript Types vs. Interfaces
3 | description: definitions, examples, and key differences between Types and Interfaces in TypeScript.
4 | ---
5 |
6 |
7 |
8 |
9 | ## 📖 Introduction
10 | TypeScript provides two powerful constructs for defining the shape of objects: **Types** and **Interfaces**. Both serve to add **type safety** and **structure** to your code, but they differ in usage and capabilities.
11 |
12 | This guide will walk you through the **definitions**, **examples**, and **key differences** between Types and Interfaces in TypeScript.
13 |
14 | ---
15 |
16 | ## ⚡️ **Type Alias**
17 | A **Type Alias** allows you to **name a type**. You can define complex data structures or combine multiple types into one.
18 |
19 | ### 📝 **When to Use Types?**
20 | - For **primitive types**, **unions**, or **intersections**.
21 | - When creating **type combinations** beyond just object structures.
22 |
23 | ### **Examples :**
24 |
25 | #### 1. **Simple Type Alias**
26 |
27 | ```ts
28 | type User = {
29 | name: string;
30 | age: number;
31 | };
32 |
33 | let person: User = { name: "Alice", age: 30 };
34 | ```
35 |
36 | This alias defines an object type with two properties: `name` and `age`.
37 |
38 | ---
39 |
40 | #### 2. **Using Intersection (&)**
41 |
42 | Intersection types combine multiple types into one, ensuring all properties from both types are present.
43 |
44 | ```ts
45 | type Address = {
46 | street: string;
47 | city: string;
48 | };
49 |
50 | type Employee = {
51 | name: string;
52 | position: string;
53 | };
54 |
55 | type EmployeeWithAddress = Employee & Address;
56 |
57 | let emp: EmployeeWithAddress = {
58 | name: "John",
59 | position: "Developer",
60 | street: "123 Main St",
61 | city: "New York",
62 | };
63 | ```
64 |
65 | Here, `EmployeeWithAddress` combines the properties of both `Employee` and `Address`.
66 |
67 | ---
68 |
69 | #### 3. **Union (|) Example**
70 |
71 | Union types allow a value to be one of several specified types.
72 |
73 | ```ts
74 | type ID = string | number;
75 |
76 | let userId: ID = 101; // Valid
77 | userId = "abc123"; // Also valid
78 | ```
79 |
80 | In this case, `ID` can be either a string or a number.
81 |
82 | ---
83 |
84 | ## ⚡️ **Interface**
85 | An **Interface** is used to define the structure of **objects** or **classes**. It ensures that the objects or instances adhere to a specified shape.
86 |
87 | ### 📝 **When to Use Interfaces?**
88 | - For **defining object shapes** or **class structures**.
89 | - When you need to **extend** from other interfaces.
90 |
91 | ### **Examples:**
92 |
93 | #### 1. **Simple Interface**
94 |
95 | ```ts
96 | interface User {
97 | name: string;
98 | age: number;
99 | }
100 |
101 | let person: User = {
102 | name: "Alice",
103 | age: 30,
104 | };
105 | ```
106 |
107 | **This interface ensures that the `person` object conforms to the `User` structure.**
108 |
109 |
110 | ---
111 |
112 | #### 2. **Extending Interfaces**
113 |
114 | You can extend one interface from another to reuse properties.
115 |
116 | ```ts
117 | interface Address {
118 | street: string;
119 | city: string;
120 | }
121 |
122 | interface Employee extends Address {
123 | name: string;
124 | position: string;
125 | }
126 |
127 | let emp: Employee = {
128 | name: "John",
129 | position: "Developer",
130 | street: "123 Main St",
131 | city: "New York",
132 | };
133 | ```
134 |
135 | In this example, `Employee` inherits all properties from `Address`.
136 |
137 | ---
138 |
139 | #### 3. **Class Implementation with Interface**
140 |
141 | ```ts
142 | interface Person {
143 | name: string;
144 | greet(): void;
145 | }
146 |
147 | class Student implements Person {
148 | constructor(public name: string) {}
149 |
150 | greet() {
151 | console.log(`Hello, my name is ${this.name}`);
152 | }
153 | }
154 |
155 | const student = new Student("Alice");
156 | student.greet(); // Output: Hello, my name is Alice
157 | ```
158 |
159 | This example shows how a class implements an interface.
160 |
161 | ---
162 |
163 | ### 🚀 **Key Differences between Type and Interface**
164 |
165 | | **Feature** | **Type Alias** | **Interface** |
166 | |------------------------------|-------------------------------------|----------------------------------|
167 | | **Primitive Types Support** | Yes (`type ID = string \| number`) | No |
168 | | **Object and Class Usage** | Yes | Yes |
169 | | **Extension** | Using Intersection (`&`) | Using `extends` |
170 | | **Union Support** | Yes (`type A = B \| C`) | No |
171 | | **Merging** | Not supported | Can be merged across declarations |
172 | | **Best Use Case** | Complex combinations, unions, primitives | Object shapes, class definitions |
173 |
174 |
175 | ---
176 |
177 | ## 💡 **Conclusion**
178 |
179 | Both **Types** and **Interfaces** help define the structure of data in TypeScript, ensuring that your code is more robust and maintainable. Use **Types** for **complex data structures** (like unions and intersections) and **Interfaces** when working with **objects or classes**.
180 |
181 | ---
182 |
183 |
184 |
185 | Happy coding with **TypeScript**! 🎉
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-type-assertions.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: TypeScript Type Assertions
3 | description: Welcome! This guide will help you understand Type Assertions in TypeScript. Type Assertions let you tell the TypeScript compiler about the type of a variable when you're sure of its type. Let’s dive in!
4 | ---
5 |
6 |
7 |
8 | Welcome! This guide will help you understand Type Assertions in TypeScript. Type Assertions let you tell the TypeScript compiler about the type of a variable when you're sure of its type. Let’s dive in!
9 |
10 | ## What Are Type Assertions?
11 |
12 | Type Assertions allow you to inform TypeScript about a variable's type. It’s like saying, “Hey TypeScript, trust me, I know this variable is a specific type.” This can help you avoid errors and make your code clearer.
13 |
14 | ## When to Use Type Assertions
15 |
16 | Use type assertions when:
17 |
18 | - You have a variable with a broad type (like `any` or `unknown`) and you know its specific type.
19 | - You want to avoid TypeScript’s default type inference when you know better.
20 |
21 | ## How to Use Type Assertions
22 |
23 | There are two ways to assert types in TypeScript:
24 |
25 | ### 1. Using Angle Bracket Syntax
26 |
27 | You can use angle brackets to assert the type.
28 |
29 | ```typescript
30 | let someValue: any = "Hello, TypeScript!";
31 | let strLength: number = (someValue).length;
32 |
33 | console.log(strLength); // Output: 17
34 | ```
35 |
36 | ### 2. Using `as` Syntax
37 |
38 | Another way is to use the `as` keyword, which is often preferred because it looks cleaner.
39 |
40 | ```typescript
41 | let someValue: any = "Hello, TypeScript!";
42 | let strLength: number = (someValue as string).length;
43 |
44 | console.log(strLength); // Output: 17
45 | ```
46 |
47 | ### Key Points :
48 |
49 | - **No Runtime Checks**: Type assertions do not change the actual value; they only affect how TypeScript treats it.
50 | - **Use Wisely**: While type assertions are useful, don't use them too much. They can lead to bugs if you're not careful.
51 | - **Keep It Clear**: Always aim for clarity in your code. If you can, define your types explicitly instead of using `any`.
52 |
53 | ### 💡 **Conclusion**
54 |
55 | Type Assertions are a handy tool in TypeScript for managing types effectively. They help you write safer and more understandable code. Use them when needed, but don’t forget about the importance of proper type definitions!
56 |
57 |
58 | Happy coding with **TypeScript**! 🎉
59 |
60 |
61 | ---
62 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-type-guards.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Type Guards in TypeScript"
3 | description: "Type Guards in TypeScript help narrow down types at runtime, ensuring that your code works safely with specific types. They allow you to check if a value belongs to a particular type, making your code more reliable and reducing errors."
4 | ---
5 |
6 | Type Guards in TypeScript help **narrow down types** at runtime, ensuring that your code works safely with specific types. They allow you to check if a value belongs to a particular type, making your code more reliable and reducing errors.
7 |
8 | ---
9 |
10 | ## What Are Type Guards?
11 |
12 | A **Type Guard** is an expression that performs a runtime check to confirm the type of a variable. Based on the result, TypeScript **refines** the type of the variable for the block of code within that condition.
13 |
14 | ---
15 |
16 | ## Example of Type Guards
17 |
18 | ```typescript
19 | function printId(id: string | number) {
20 | if (typeof id === "string") {
21 | console.log(`ID in string format: ${id.toUpperCase()}`);
22 | } else {
23 | console.log(`ID as a number: ${id}`);
24 | }
25 | }
26 |
27 | printId("abc123"); // ✅ Output: ID in string format: ABC123
28 | printId(101); // ✅ Output: ID as a number: 101
29 | ```
30 |
31 | Here, the `typeof` check acts as a type guard, ensuring `id` is treated correctly as either a string or a number.
32 |
33 | ---
34 |
35 | ## Built-in Type Guards
36 |
37 | 1. **`typeof` Operator**: Used to check primitive types like `string`, `number`, `boolean`, etc.
38 |
39 | ```typescript
40 | if (typeof value === "string") {
41 | /* ... */
42 | }
43 | ```
44 |
45 | 2. **`instanceof` Operator**: Used to check if an object is an instance of a class.
46 |
47 | ```typescript
48 | class Car {
49 | drive() {
50 | console.log("Driving...");
51 | }
52 | }
53 | const myCar = new Car();
54 |
55 | if (myCar instanceof Car) {
56 | myCar.drive(); // ✅ Works, myCar is confirmed to be a Car
57 | }
58 | ```
59 |
60 | ---
61 |
62 | ## Custom Type Guards
63 |
64 | You can create **custom type guards** using functions with a special `is` return type. This is useful when working with more complex types.
65 |
66 | ### Example:
67 |
68 | ```typescript
69 | type Dog = { bark: () => void };
70 | type Cat = { meow: () => void };
71 |
72 | function isDog(animal: Dog | Cat): animal is Dog {
73 | return (animal as Dog).bark !== undefined;
74 | }
75 |
76 | function makeSound(animal: Dog | Cat) {
77 | if (isDog(animal)) {
78 | animal.bark(); // ✅ TypeScript knows it's a Dog here
79 | } else {
80 | animal.meow(); // ✅ TypeScript knows it's a Cat here
81 | }
82 | }
83 | ```
84 |
85 | In this example, `isDog` is a **custom type guard** that tells TypeScript whether the given `animal` is a Dog.
86 |
87 | ---
88 |
89 | ## Using `in` Operator
90 |
91 | The **`in` operator** is another way to narrow types by checking if a property exists in an object.
92 |
93 | ```typescript
94 | type Admin = { role: string };
95 | type User = { username: string };
96 |
97 | function printInfo(person: Admin | User) {
98 | if ("role" in person) {
99 | console.log(`Admin Role: ${person.role}`);
100 | } else {
101 | console.log(`User Name: ${person.username}`);
102 | }
103 | }
104 | ```
105 |
106 | ---
107 |
108 | ### Key Points :
109 |
110 | - **Type Guards** help TypeScript determine a variable's type at runtime.
111 | - **Built-in Guards**: Use `typeof` for primitives and `instanceof` for class instances.
112 | - **Custom Guards**: Define your own guards with functions that return `animal is Type`.
113 | - **`in` Operator**: Check for property existence to narrow object types.
114 |
115 | ---
116 |
117 | ### 💡 **Conclusion**
118 |
119 | Type Guards make your code safer and more predictable by narrowing down types at runtime. They let TypeScript understand what type a value will have, reducing errors and improving developer experience.
120 |
121 | Happy coding with **Typescript**! 🎉
122 |
123 |
124 |
125 | ---
126 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript-utility-types.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Utility Types in TypeScript"
3 | description: "Welcome! In this guide, we’ll learn about Utility Types in TypeScript. These built-in types help you manipulate and transform other types, making your code cleaner and more manageable. Let’s explore how they work!"
4 | ---
5 |
6 | Welcome! In this guide, we’ll learn about **Utility Types** in TypeScript. These built-in types help you manipulate and transform other types, making your code cleaner and more manageable. Let’s explore how they work!
7 |
8 | ---
9 |
10 | ## What Are Utility Types?
11 |
12 | Utility types in TypeScript are pre-defined types that allow you to quickly modify or extract information from other types. They save you time by automating common tasks like making fields optional, readonly, or picking specific properties from an object.
13 |
14 | ---
15 |
16 | ## Commonly Used Utility Types
17 |
18 | Let’s look at some of the most popular utility types and how they can be useful.
19 |
20 | ---
21 |
22 | ### 1. **`Partial`**
23 |
24 | Converts all properties of a type to **optional**.
25 |
26 | ```typescript
27 | type User = {
28 | id: number;
29 | name: string;
30 | email: string;
31 | };
32 |
33 | const updateUser = (user: Partial) => {
34 | console.log(user);
35 | };
36 |
37 | updateUser({ name: "Saurabh" }); // ✅ Valid, only name provided
38 | ```
39 |
40 | #### Use Case :
41 |
42 | When updating part of an object without requiring all fields.
43 |
44 | ---
45 |
46 | ### 2. **`Required`**
47 |
48 | Makes all properties **required** (opposite of `Partial`).
49 |
50 | ```typescript
51 | type User = {
52 | id?: number;
53 | name?: string;
54 | email?: string;
55 | };
56 |
57 | const createUser = (user: Required) => {
58 | console.log(user);
59 | };
60 |
61 | createUser({ id: 1, name: "Saurabh", email: "test@example.com" }); // ✅ Valid
62 | ```
63 |
64 | #### Use Case :
65 |
66 | When you need to ensure all properties are present.
67 |
68 | ---
69 |
70 | ### 3. **`Readonly`**
71 |
72 | Makes all properties **read-only**, preventing them from being modified.
73 |
74 | ```typescript
75 | type User = {
76 | id: number;
77 | name: string;
78 | };
79 |
80 | const user: Readonly = { id: 1, name: "Saurabh" };
81 | // user.id = 2; // ❌ Error: Cannot assign to 'id' because it is read-only
82 | ```
83 |
84 | #### Use Case :
85 |
86 | When you want to create immutable objects.
87 |
88 | ---
89 |
90 | ### 4. **`Pick`**
91 |
92 | Selects a **subset of properties** from a type.
93 |
94 | ```typescript
95 | type User = {
96 | id: number;
97 | name: string;
98 | email: string;
99 | };
100 |
101 | type UserPreview = Pick;
102 |
103 | const user: UserPreview = { id: 1, name: "Saurabh" };
104 | console.log(user);
105 | ```
106 |
107 | #### Use Case :
108 |
109 | When you need only specific fields from a type.
110 |
111 | ---
112 |
113 | ### 5. **`Omit`**
114 |
115 | Removes certain properties from a type.
116 |
117 | ```typescript
118 | type User = {
119 | id: number;
120 | name: string;
121 | email: string;
122 | };
123 |
124 | type UserWithoutEmail = Omit;
125 |
126 | const user: UserWithoutEmail = { id: 1, name: "Saurabh" };
127 | console.log(user);
128 | ```
129 |
130 | #### Use Case :
131 |
132 | When you want to exclude some properties from an object type.
133 |
134 | ---
135 |
136 | ### 6. **`Record`**
137 |
138 | Creates a type with a **fixed set of keys and values**.
139 |
140 | ```typescript
141 | type Role = "admin" | "user" | "guest";
142 |
143 | const permissions: Record = {
144 | admin: ["read", "write", "delete"],
145 | user: ["read", "write"],
146 | guest: ["read"],
147 | };
148 |
149 | console.log(permissions);
150 | ```
151 |
152 | #### Use Case :
153 |
154 | When you need to map keys to specific values.
155 |
156 | ---
157 |
158 | ### 7. **`Exclude`**
159 |
160 | Removes specific types from a union.
161 |
162 | ```typescript
163 | type Status = "success" | "error" | "pending";
164 |
165 | type NonPendingStatus = Exclude;
166 |
167 | let status: NonPendingStatus = "success"; // ✅ Valid
168 | // status = "pending"; // ❌ Error: Type '"pending"' is not assignable
169 | ```
170 |
171 | #### Use Case:
172 |
173 | When you want to exclude specific values from a union type.
174 |
175 | ---
176 |
177 | ### 8. **`Extract`**
178 |
179 | Extracts only the matching types from a union.
180 |
181 | ```typescript
182 | type Status = "success" | "error" | "pending";
183 |
184 | type OnlyPending = Extract;
185 |
186 | let status: OnlyPending = "pending"; // ✅ Valid
187 | ```
188 |
189 | #### Use Case:
190 |
191 | When you need to filter out only certain types from a union.
192 |
193 | ---
194 |
195 | ### 9. **`NonNullable`**
196 |
197 | Removes `null` and `undefined` from a type.
198 |
199 | ```typescript
200 | type User = {
201 | id: number | null;
202 | name?: string;
203 | };
204 |
205 | type NonNullableId = NonNullable;
206 |
207 | let id: NonNullableId = 123; // ✅ Valid
208 | // id = null; // ❌ Error: 'null' is not assignable
209 | ```
210 |
211 | #### Use Case :
212 |
213 | When you want to make sure a value is neither `null` nor `undefined`.
214 |
215 | ---
216 |
217 | ### 💡 **Conclusion**
218 |
219 | Utility types in TypeScript make working with types much easier by helping you modify and reuse them effectively. They improve your code’s clarity and reduce boilerplate.
220 |
221 | ### Summary of Utility Types:
222 |
223 | - **`Partial`**: Makes fields optional.
224 | - **`Required`**: Makes fields required.
225 | - **`Readonly`**: Makes fields read-only.
226 | - **`Pick`**: Selects specific fields.
227 | - **`Omit`**: Excludes specific fields.
228 | - **`Record`**: Maps keys to values.
229 | - **`Exclude`**: Removes types from unions.
230 | - **`Extract`**: Extracts matching types.
231 | - **`NonNullable`**: Removes `null` and `undefined`.
232 |
233 | Use these types wisely to write cleaner, safer, and more efficient TypeScript code!
234 |
235 | Happy coding with **Typescript**! 🎉
236 |
237 |
238 |
239 | ---
240 |
--------------------------------------------------------------------------------
/src/content/docs/typeScript/typescript.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: What is TypeScript
3 | description: discussion about typescript
4 | ---
5 |
6 | TypeScript is a programming language developed by Microsoft. It extends JavaScript by adding static types, which helps catch errors during development and makes code more robust and maintainable. Because TypeScript is a superset of JavaScript, it allows developers to gradually adopt it by adding types to existing JavaScript code. This means you can still run all your JavaScript code within a TypeScript environment while benefiting from the added features and type safety that TypeScript provides.
7 |
8 | ## Why TypeScript
9 |
10 | - Avoid Bugs in Development
11 | - Type Safety
12 | - Increase Development Speed
13 | - Additional Features
14 | - Better Code Completion
15 | - Better Code Readability
16 | - Better Code Documentation
17 | - Better Code Performance
18 |
--------------------------------------------------------------------------------
/src/env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "astro/tsconfigs/strict"
3 | }
4 |
--------------------------------------------------------------------------------