teleren/devto huggingface dataset:
[ Network ] - Cookie & Session
Tags: network, http, cookie, session
Published: 2022-03-22 14:59:23

사실 개발을 하다 보면 저절로 알게 되는 파트인듯하다.

하지만 두루뭉실하게 알고 지나가는 경우가 많고,
최근에는 기술 면접도 대비를 해야 해서 이렇게 글로 남겨보려고 한다.

먼저 쿠키와 세션에 대해 알기 전에, HTTP 프로토콜에 특징을 알아야 한다.
그래야 **왜 쿠키와 세션을 사용하는지** 알 수 있기 때문이다.

---

# HTTP 프로토콜의 특징
#### 1. Connectionless(비연결지향)
- 클라이언트가 요청을 한 후, 응답을 받으면 그 연결을 끊어버리는 특징. HTTP 프로토콜은 Client가 요청을 보내고, 서버에서 응답을 보낸 후 접속을 끊어버린다.

#### 2. Stateless(상태정보 유지 안함)
- 통신이 끝나면 상태를 유지하지 않는 특징이다.
연결을 끊는 순간 Client와 서버의 통신이 끝나고, 상태 정보는 유지하지 않는 특징이  있다.

위 두 가지 공통적인 특징으로 보아 HTTP 프로토콜은 한 번의 요청이 끝나면 접속을 끊으며 상태를 유지하지 않는다.

즉, 한 번의 요청이 발생한 후 다시 백지가 된다고 생각하면 편할 것 같다.
이러한 이유 때문에, 우리는 쿠키와 세션을 사용한다.

---

# 🍪 Cookie
#### 1️⃣ 쿠키란?
1. 쿠키란, 클라이언트(브라우저) 로컬에 저장되는 작은 데이터 파일이다.
2. 쿠키의 만료일이 없다면, 브라우저의 탭을 닫거나 종료해도 쿠키는 사라지지 않는다.
3. 쿠키는 클라이언트의 상태 정보를 로컬에 저장했다가 참조한다.
4. 하나의 클라이언트당 300개의 쿠키 저장이 가능하다. 각 도메인당 20개의 쿠키를 가질 수 있고, 쿠키 하나의 크기는 4KB이다.

#### 2️⃣ 쿠키의 구성 요소
- **이름** : 각각의 쿠키를 구별하기 위해 사용되는 이름
- **값** : 쿠키에서 가지고 있어야 할 값
- **유효시간** : 말 그대로 쿠키의 유효시간
- **도메인** : 쿠키를 전송할 도메인
- **경로** : 쿠키를 전송할 요청 경로

#### 3️⃣ 쿠키는 어떻게 동작하는가?
1. 클라이언트에서 서버로 요청
2. 서버에서 쿠키 생성
3. 서버가 클라이언트에게 응답을 할 때, HTTP 헤더에 생성한 쿠키를 담아 응답
4. 서버에게서 받은 쿠키를 클라이언트(로컬)에 저장
5. 해당 서버에게 다른 요청을 보낼 때, 쿠키가 사용자의 로컬에 존재한다면, 해당 쿠키를 헤더에 담아 요청

#### 4️⃣ 쿠키의 사용 예시
1. 사이트에 방문 시, 아이디 및 비밀번호 자동 입력
2. 팝업창의 "오늘 이 창을 다시 보지 않기" 체크

---

# 💾 Session
#### 1️⃣ 세션이란?
일정 시간동안 동일한 사용자로 부터 들어오는 요청을 하나의 상태로 보고, 그 상태를 일정 시간동안 유지시켜주는 기술이다.

여기서의 **`일정 시간`**이란, 사용자가 브라우저를 통해서 서버에 접속한 시점부터, 브라우저를 종료하여 연결을 끝내는 시점을 말한다.

다시 말해, 사용자가 서버에 접속한 상태를 하나의 상태 단위로 보고, 그것을 **`세션`**이라고 한다.

#### 2️⃣ 세션의 특징
1. **웹 서버에** 웹 컨테이너의 상태를 유지하기 위한 **정보를 저장한다.**
2. 클라이언트(로컬)가 아닌 웹 서버에 저장되는 쿠키
3. 세션을 브라우저를 종료했거나 웹 서버에서 세션을 삭제했을 때만 삭제가 된다. 쿠키보다 보안에 좋다.
4. 쿠키는 총 300개, 도메인당 20개를 저장할 수 있었는데, 세션은 웹 서버에서 허용하는 한 제한 없이 저장이 가능하다.
5. 각 클라이언트에게 고유한 Session ID를 부여한다.
이 Session ID로 각 클라이언트를 구분하는 것이다.

#### 3️⃣ 세션의 동작 순서
1. 클라이언트가 서버에 접속 시 Session ID를 발급 받는다.
2. 클라이언트는 서버로부터 발급받은 Session ID에 대해 쿠키를 이용하여 저장한다. 이 때, 서버도 해당 Session ID를 서버에서 쿠키를 이용해 갖고 있는다. 그래서 서버에서 저장하는 쿠키라고 하는 것이다.
3. 클라이언트는 서버에 요청을 보낼 때, 가지고 있던 쿠키의 Session ID를 같이 보낸다.
4. 서버는 Session ID를 받아서 클라이언트 정보를 가져와 사용한다.

#### 4️⃣ 세션의 사용 예시
- 로그인 같이 보안상 중요한 작업을 수행할 때 사용

---

# 쿠키와 세션의 차이
쿠키와 세션의 차이점 중에서 제일 중요한 몇가지만 나눠보려고 한다.

#### 1️⃣ 저장 위치
쿠키는 클라이언트의 로컬에 저장되고, 세션은 서버에 저장이 된다.

이 말은 다시 말해, 쿠키는 클라이언트의 리소스를 사용하게 되고, 세션은 서버의 리소스를 사용하게 된다.

이따 뒤에서도 설명을 하겠지만, 세션은 서버측에서 관리를 하기에 보안에 좋다.

그렇다면 세션만 사용하면 될텐데 왜 쿠키를 사용할까?

위에도 언급했듯, 세션은 서버의 자원을 사용한다. 따라서 많은 클라이언트가 요청을 하여 무분별하게 세션을 만들다보면 서버의 메모리가 감당이 안되어 서버의 속도가 느려질 수도 있고, 잘못하면 다운이 될 수도 있다.

이러한 차원에서 쿠키가 존재하며 필요한 이유이다.

#### 2️⃣ 속도
쿠키는 클라이언트에서 바로 서버에게 보낸다.
하지만 세션의 방식은, 서버가 Session ID를 받으면 서버 내에서 저장해뒀던 쿠키를 이용해 처리가 필요하기 때문에 속도적인 측면에서는 쿠키를 사용하는 것이 더 빠르다.

얼마나 속도 차이가 나는지는 아직 공부가 더 필요하다.

#### 3️⃣ 보안
쿠키는 클라이언트가 보관을 하지만, 세션은 서버가 관리를 하기에,
보안적인 측면으로는 세션이 더 우수하다.
Paracetamol.js💊| #83: Explica este código JavaScript
Tags: javascript, spanish, webdev, beginners
Published: 2022-03-22 14:51:23

## **Explica este código JavaScript**

```js
var nombre = "Camila";
let apellido = "Rodriguez";
const edad = 25;

const getDatosPersonales = () => {
  console.log(nombre);
  console.log(apellido);
  console.log(edad);
}

console.log(getDatosPersonales());
```

A. `Camila`, `Rodriguez`, `25`
B. `Camila`, `undefined`, `undefined`
C. `ReferenceError`
D. `undefined`, `Rodriguez`, `25`

Respuesta en el primer comentario.

---
Speedy Typer Game
Tags: javascript, firebase, gamedev, vanilla
Published: 2022-03-22 14:49:53

https://lucapu88.github.io/speed-typer-game/

I have completed some changes to my game, now I have entered a global ranking with the help of FireBase!
The game tests your writing skills on the keyboard. It consists of rewriting as many words as possible in 30/60 seconds, at various speeds. At the end of the game you will be able to enter your score in the global leaderboard, and the top 5 names for each mode will be shown.
Have fun competing against any global user and show how good you are at typing.
If you don't want to compete but you just want to practice, and improve in writing with 10 fingers, you can choose between 2 other modes:
Exercise, where you train timeless and unscored with one word at a time.
Sentences, where you train by copying entire sentences and measuring your writing speed.
Як ти? How are you? 💙💛
Tags: career, watercooler, mentalhealth, startup
Published: 2022-03-22 14:46:52

Як ти? How are you? - this is a new way of saying I love you, I care about you. 
On the image above, the person hasn’t been online for 2 days to see the message. Are they in a bomb shelter? Are they still alive?

Fuck this war in Ukraine.

Somebody I love has lost their business and home. Somebody has lost their job and was displaced. Somebody got detained for 15 days. Somebody lost a leg. Somebody lost a husband and a kid. I am talking about the people I know personally. These are not Instagram stories, these are people, these are lives.

On the first week of the war I felt almost guilty for being safe, guilty for daring to even think about our startup that we had to put on pause.

“_Put on the life west on yourself and then help others_” - the life-saving manuals say. That’s what Lera (my co-founder) and I did to our emotional health, in exactly this order.

Two of us [recorded an audio diary](https://anchor.fm/communities-show/episodes/How-are-you-e1fti2n), our emotional journey as a non-representative example of how to live with war and suffering in our backyard. 

We didn’t hide, we didn’t move on, we decided to live with it and stay sane, help others. The pain didn’t go away, but at least we found a reason to be beyond the two weeks until “the life goes back to normal”.

Our new reason to be is [the jobs page for Ukrainians](https://gamedev.camp/ukraine).
Yes, it is focused on one single country and one single industry. But we do what we can do well:

* all jobs have direct HR contacts and specify if English or Russian is enough
* all companies specify if remote is an option
* we have a Telegram chat to directly help all involved with Lithuanian games industry folks helping Ukrainians

The next step - meetups and events for Ukrainian games professionals to meet the locals here in Vilnius. 

And by locals I also mean Belarusians who had to flee their country that is temporarily occupied by kremlin. Yes, Belarusian gamedevs are locals now, and they also want to welcome Ukrainians to Lithuania. 💙💛

> This text feels like a dump of personal emotions and it is. I tried to show how I mentally coped with the war in the backyard (where my family and friends have to fight russia) and was able to stay somewhat sane and relatively productive. I am not pretending to be a role model and a perfect example. But here's my way.
How to fix external domain problem not resolving dns name on godaddy?
Tags: godaddydns, dns
Published: 2022-03-22 14:43:28

Today I faced a problem with one domain client. My domain is registered on https://registro.br and my website hosting is on godaddy. But the domain address was not being resolved properly. So I discovered that.

I need to enter on godaddy: domains setttings and add a domain type A to my hosting ip address on godaddy. This way works. 

Obviously my domain on https://registro.br/ I change the dns to godaddy too.
WSL2, VM, Dual Boot, Proxmox怎麼選?
Published: 2022-03-22 14:31:48

更多會員限定文章可以到[patreon觀看](https://www.patreon.com/wade3c)

-----

# WSL2, VM, Dual Boot, Proxmox怎麼選?

現在如果你想在一台電腦上使用多種不同的OS，其實有非常多的選擇

## WSL2

WSL2是微軟透過Hyper-V開啟的虛擬機，讓我們不用手動去建立VM

WSL2在21H2後支援了WSLg以及GPU，這樣一來我們就可以在Windows直接使用到Linux內的GUI且能讓Linux也吃到GPU的資源

這對於一般的開發用途來說已經非常足夠，**尤其是你只打算使用CLI時**

## VM

但是如果你想要體驗到更**完整的Linux Desktop**，我還是會建議使用虛擬機

不論是Virtual box或是VMware workstation，都能讓你更接近原生Linux的使用體驗

缺點是目前他們**在一般消費級的顯卡上都不支援GPU pass-thru**

## Dual Boot

想要在體驗完整的桌面版Linux的同時又能使用到GPU的話，雙系統是個很好的選擇

但是你必須要在透過grub/ bios才能選擇開機時要用哪個系統

如果你是::遠端開機(WOL)的話，你就看不到選擇的頁面:: (KVM over IP是個解法)

必須先進到Linux才能更改grub預設啟動的OS

## Docker

如果只是要輕度使用Linux來開發的話，Docker是個非常好的選擇

**要使用到GPU功能也可以搭配Nvidia-docker **(Windows必須使用WSL2)

## Proxmox

他和前面幾個比較不同是hypervisor，作為長期啟動的中介層

讓我們可以開啟非常多種不同型態的虛擬機，且支援GPU pass-thru

但是**上手難度也是這裡面最高的**
C# Authorization attribute and how to override it
Tags: csharp, aspdotnet, programming, webdev
Published: 2022-03-22 14:26:36

Disabling or enabling certain actions or endpoints in your controllers/API is relatively easy to do in ASP.NET, all you need is to add Authorize attribute to a Controller or Action with the desired roles and you are done.

```CSharp
[Authorize] // Only authenticated users will be able to access this controller
public class MyController : BaseController {
  [AllowAnonymous] //anyone can access this action, controller [Authorize] attribute is ignored
  public ActionResult AnyoneCanAccessIt(){
     //...code
  }
  [Authorize(Roles="Admin,QA")]
  public ActionResult Only_Role_Admin_and_QA_Can_Access_This(){
    //...code
  }
  public ActionResult All_Authenticated_Users_Can_Access_This_Action(){
   //...code
  }
}
```
...and that is it

Recently I had to disable access to a certain functionality for everybody so I just put `Authorization `attribute with an unexisting role at the controller and the problem was solved, at least I thought so. 

```CSharp
[Authorize(Roles="Not allowed")]
/* access to this controller is restricted to all users without this role. 
We don't have this role in our system so no one can access it.
*/
public class MyController : BaseController {
   //.. bunch of actions
}
```

But I forgot that there is only one method that needs to stay accessible to all authorized customers. One solution was to remove `Authorize` attributes from the controller and then disable access to each action individually by applying `Authorize `attribute to each of them. That was a lot of work so I needed to find a different solution! 
The best solution for this kind of problem is `OverrideAuthorization` attribute which removes any previously set `Authorize` logic and starts from the beginning.

All I needed to do is Add `OverrideAuthorization `attribute to the action I want to be accessible, and then below it set Authorize attribute again.

```CSharp
[Authorize(Roles="Not allowed")]
/* access to this controller is restricted to all users without this role. 
We don't have this role in our system so no one can access it.
*/
public class MyController : BaseController {
   //.. bunch of actions

  [OverrideAuthorization] // overrides authorization filters defined at a higher level
  [Authorize] // will make this action only accessible to authenticated users
  public ActionResult My_Action_That_Needs_Access_Afterall(){
    //... code
  }
}
```
SPA application error 404 on refresh
Tags: htaccess, redirect
Published: 2022-03-22 14:14:54

If you deploy your SPA application on a server as Godaddy or other service and try to access a url diferent from root folder as /about and has an error 404 you can try to solve your problem following this documentation from react:
[https://create-react-app.dev/docs/deployment/](https://create-react-app.dev/docs/deployment/)

But the fast answer for your question is to create a .htaccess file on your server and past the following code:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
How to change the URI (URL) for a remote Git repository?
Tags: git, beginners, tutorial, github
Published: 2022-03-22 14:09:47

## What is Git?
Git is the world's most popular distributed version control system used by many open-source and commercial projects. It allows you to collaborate on projects with your fellow developers, keep track of your code changes, revert to previous stages, create branches, and more. Linus Torvalds (the creator of Linux) developed Git.

Git is software for tracking changes in any set of files, usually used for coordinating work among programmers collaboratively developing source code during software development. Its goals include speed, data integrity, and support for distributed, non-linear workflows.

A version control system is a system that keeps a record of the changes in a file (or multiple files) over a period. This is so that a user may return to a previous version of the system's software whenever necessary.

## Features of Git

- Tracks history.
- Free and open source.
- Supports non-linear development.
- Creates backups.
- Scalable.
- Supports collaboration.
- Branching is easier.
- Distributed development.

## What is Git Remote URI(URL)?
Git remote is a pointer that refers to another copy of the repository that is usually hosted on a remote server.

In some situations, like when the remote repository is migrated to another host, you need to change the remote’s URL.

In this tutorial, you are going to learn how you can change the URL of a Git remote easily.

## Changing a Git Remote’s URL
Each Git repository can have zero or more Git remotes linked to it. When you clone a repository, the name of the remote is set automatically to **origin** and points to the repository that you cloned from.

Follow the steps below to change the URL of a remote:
1 - Change to the directory where the repository is located:
```
cd /path/to/repository
```
2 - Run git remote to list the existing remotes and see their names and URLs:
```
git remote -v
```
3 - Use the git remote set-url a command followed by the remote name, and the remote’s URL:
```
git remote set-url <remote-name> <remote-url>
```
If you’re changing to HTTPS, the URL will look something like this:
```
https://gitserver.com/user/repo_name.git
```
If you’re changing to SSH, the URL will look like this:
```
git@gitserver.com:user/repo_name.git
```
4 - Verify that the remote’s URL was successfully changed by listing the remote connections:
```
git remote -v
```
That’s it. You have successfully changed the URL of the remote.
**Thank you** for reading this blog.
Automatically Sorting Tailwind Classes with Prettier
Tags: webdev, tailwindcss
Published: 2022-03-22 14:02:21

Ever since [TailwindCSS](https://tailwindcss.com/) was released there has been a silent battle as to what is the best order for Tailwind's utility classes. I like to believe there is now a definitive answer.

## What Is Tailwind?
Tailwind is a utility first CSS framework that aims to get you to use as little CSS as possible. 

Up until now, there hasn't been a definitive answer to how to order the classes - which is fitting considering the nature of Tailwind. 

Extensions like [Headwind](https://marketplace.visualstudio.com/items?itemName=heybourn.headwind) have tried to give some rules to this.

> ## Enter Prettier Plugin Tailwind

---

## How Does The Plugin Work?
It uses Prettier's **format on save** and Tailwind's method of sorting classes. Meaning classes in the **base** will be first, followed by ones in **components**, then lastly the ones in **utilities**:


> ![usorted.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1647955387804/uLzZqKy8K.png)
unsorted classes

```js
@tailwind base;
@tailwind components;
@tailwind utilities;
```

>![sorted.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1647955477161/6w_3BSBsu.png)
classes after sorting

If you made custom classes, they would go first, for example:

>![custom...png](https://cdn.hashnode.com/res/hashnode/image/upload/v1647955616774/LBccr-9Ov.png)
My custom classes


>![custom.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1647955705385/rFs4j51_H.png)
How they are sorted after saving

---

## How To Start Using The Plugin
After making sure you have a `package.json` in your project, simply run:

```sh
npm install -D prettier prettier-plugin-tailwindcss
```

Now any time you save, your classes will be automatically sorted.

## Formatting An Existing Project
If you have an existing project that you would like to use the plugin on, simply run the above command then: 
1. Check which files need formatting
```sh
npx prettier --check .
```

2. Write to those files or folders:
```sh
npx prettier --write [dir name]
```

---

## Conclusion
How do you order your Tailwind classes? Would you consider using the plugin?

>*image credit: TailiwindCSS*

---

###  Thank you for reading, let's connect!
Thank you for visiting this little corner of mine. Let's connect on [**Twitter**](https://twitter.com/Psypher1), [**Polywork**](https://www.polywork.com/psypher1) and [**LinkedIn**](https://www.linkedin.com/in/jamesmidzi/)
What am I doing?! - A logbook
Tags: beginners, webdev, codenewbie
Published: 2022-03-22 13:55:50

Hi there! I‘m Ann-Kathrin, the new one. The Baby. The Noob. I‘m a dietician and linguist who fell in love with coding about a year ago, when my son was just a tiny baby. How time passes!

##Why this?

I have decided to track my learning-journey inside this community. For one, to hold myself accountable and also because my self-doubts could definitely use a kick in the butt! (I read this community can be supportive…😬) I mean, from the moment I started learning, playing around with HTML, CSS, JavaScript and Python I knew that this is something I want to do. So complex and yet so fulfilling to learn. It’s the first time I’m doing something that could possibly one day earn me a living and it feels light and easy. Not all the time but most of the time. And that’s a massive improvement! Not having to push myself everyday to learn and to practice is such a pleasure. 

##Never let your doubts… (🤢 cheesy but correct)

Again and again during the last year I have let my doubts hold me back. What a waste of time! And this is the most important (yet cheesy) thing I took away from this so far. Never again will I let doubts and pondering keep me from doing things I like. How far could I be now had I spent my free time last year coding, not just thinking about it? Well, moving forward now. 

##What is there so far?
By now I know the basics of HTML and CSS with Flexbox (tried out a few simple websites to practise, thanks to Daniel Scott and his team at [bringyourownlaptop](bringyourownlaptop.com) - Dan is an amazing teacher. Although Designer not Developer, his class gave me courage!) with some Bootstrap coming. Then some more yet unknown to me CSS Concepts trough [freeCodeCamp](http://www.freecodecamp.org). Transferring this into a small project of my own will be the next task. 
On the side I am learning basic concepts of programming languages like JavaScript and Python through an App just to get familiar with the Vocabulary and the way of thinking. All of this whenever my not-so-tiny-anymore favourite human being is asleep. I still need to figure out how to professionalise this behemoth of a journey a little more.

I’m planning to post about my progress every other week. Can’t wait to see where I am at in 5 posts time. 

Have a great two weeks, guys! Here, there’s spring coming out just now 🌸☀️🍻 Something small to enjoy while the world is still burning…
React, Vue and Svelte: Comparing Lifecycle methods
Tags: javascript, react, vue, svelte
Published: 2022-03-22 13:45:43

## Lifecycle in...
### React

```jsx
import { useEffect } from 'react';

const Component = () => {
  useEffect(() => {
    console.log("the component is now mounted.")
  },[])
}
```

```jsx
import { useEffect } from 'react';

const Component = () => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("the component is updated.")
  },[count])
}
```

```jsx
import { useEffect } from 'react';

useEffect(() => {
	//your code goes here
    return () => {
      //your cleanup code codes here
      console.log("the component is destroyed.")
    };
},[]);
```

### Vue
[Link](https://stackblitz.com/edit/vitejs-vite-vt7aqc?file=src/App.vue)

```jsx
<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  console.log("the component is now mounted.")
})
</script>
```

```jsx
<script setup>
import { onUpdated } from 'vue';

onUpdated(() => {
  console.log("the component is updated.")
})
</script>
```

```jsx
<script setup>
import { onUnmounted } from 'vue';

onUnmounted(() => {
  console.log("the component is destroyed.")
})
</script>
```

### Svelte
[Link](https://stackblitz.com/edit/vitejs-vite-9nd3jb?file=src/App.svelte)

```jsx
<script>
  import { onMount } from 'svelte';
  onMount(() => {
    console.log("the component is now mounted.")
  });
</script>
```

```jsx
<script>
  import { afterUpdate } from 'svelte';
  afterUpdate(() => {
    console.log("the component is updated.")
  });
</script>
```

```jsx
<script>
  import { onDestroy } from 'svelte';
  onDestroy(() => {
    console.log("the component is destroyed.")
  });
</script>
```
Conditional Statements: Part 2
Tags: javascript, typescript, beginners, tutorial
Published: 2022-03-22 13:39:52

## The issue with legacy conditional statements.
The main issue is, it is ugly and boring. See the [Part 1](https://dev.to/rahulrajrd/conditional-statements-1okd).

It takes a lot of time to write conditions and maintain them consider the below.

```typescript
  private demo(myVar: string): string {
    if(myVar === 'condition') {
      return myVar.substring(1,3);
    }
    if(myVar === 'demo') {
      return myVar.substring(1,2);
    }
    if(myVar === 'thing') {
      return myVar.substring(1,4);
    }
    if(myVar === 'demo1') {
      return myVar.substring(1,5);
    }
    if(myVar === 'demo5') {
      return myVar.substring(1,2);
    }
    return '';
  }
```

Now the above code can be good in some case but we can do better.
**USING OBJECT FOR CONDITIONING**

```typescript
  private demo1(myVar: string): string {
    const myObject: { [key: string]: string; } = {
      'condition': myVar.substring(1,3),
      'demo': myVar.substring(1,2),
      'thing': myVar.substring(1,4),
      'demo1': myVar.substring(1,5),
      'demo5': myVar.substring(1,2),
    }
    return myObject[myVar];
  }

  demo1('condition'); 
```
It will work same as the above `if` statements but it is a clean code.

Want to check the default condition as well?

```typescript
  private demo1(myVar: string): string {
    const myObject: { [key: string]: string; } = {
      'condition': myVar.substring(1,3),
      'demo': myVar.substring(1,2),
      'thing': myVar.substring(1,4),
      'demo1': myVar.substring(1,5),
      'demo5': myVar.substring(1,2),
      default: '',
    }

    if(!myObject[myVar]) return myObject['default'];
    return myObject[myVar];
  }
```
This reduces the overall cognitive complexity as well.

With this we can even have function calls.

```typescript
  public coc(troopName: string, quantity: number): string {
    const bookForCOC: { [key: string]: any } = {
      'barbarian': () => quantity > 30 ? 'Use it behind kind' : 'Use it to destroy',
      'archer': () => quantity > 20 ? 'Use it behind queen' : 'Use it to destroy',
      'balloon': () => quantity > 20 ? 'Use it behind dragons' : 'Use it after air defense is destroyed',
      'dragon': () => quantity > 3 ? 'Use it at a single place' : 'Use it anywhere else',
      default: () => 'Use some good troops to win'
    }

    if(!bookForCOC[troopName]) return bookForCOC['default']();
    return bookForCOC[troopName]();
  }
```
This can be used as an alternative for conditional statements

If you like the post follow me for more
{% user rahulrajrd%}
Ansible 5.5.0 has been released
Tags: automation, ansible
Published: 2022-03-22 13:22:32

Ansible users will be interested to know that Ansible just received a major version update. In addition to a curated set of Ansible Collections, the **Ansible 5.5.0 package also includes ansible-core 2.12**, which is a significant update from Ansible 4 versions, which included ansible-core 2.11. The new ansible-core requires the use of Python 3.8, unlike ansible-core 2.11, which still supports the use of Python 3.6. 

So those of you still using the earlier Python versions should keep in mind that when you upgrade Ansible, you also need to upgrade your Python version. And since ansible-core 2.12 is a major update from the version used in Ansible 4, check your playbooks for any potential compatibility issues.

But as Ansible 5.5.0 brings updates to 19 Ansible Collections, providing a bunch of new modules and plugins, you shouldn't hesitate and get the new version asap! ;)

Get more info here: https://groups.google.com/g/ansible-announce/c/4sbFT7aVklY?pli=1