teleren/devto huggingface dataset:
Don’t Use Switch or If-Else in JavaScript, Instead, Try This
Tags: javascript, beginners, tutorial, programming
Published: 2022-04-26 05:03:38

Instead of Write better switch and if…else statement in JavaScript with object

## What is the switch statement?

The switch statement evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

![What is the switch statement in javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fy0rjd0911t24yduwuz.png)

## Problems with switch

The switch case is a little difficult to read and a bit ancient, and it’s prone to debugging problems.

The odd thing about the switch case is that you have to include the keyword break at the end of each case to prevent the control from moving to the next.

in addition to that, it’s a disaster when it comes to mapping complex scenarios, which can lead to difficult debugging and nested errors.

Every time we write a switch statement, we must exercise extreme caution.

The joy of writing code is curtailed when you have to be extra cautious and that causes a huge problem.

**Using objects**

Let’s set up a match function to simulate switch cases


![how to use objects in javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/layi13w7h6vpfs8t50fc.png)

And you can do something like this :

![how to use javascript objects instead of if else and switch statment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u1a4l5dzrkkdjiii50yg.png)

An object can be used as an alternative to the switch statement.

Using Object one can implement a keyed method lookup.

**Summing up**

This isn’t to say that the switch statement isn’t useful or that using object literals is always the best option. Object literals as switches, on the other hand, should become another tool in your javascript toolbox.

You can find the full code we implemented in this post here.
That’s it

I hope you enjoyed it!

Leave any questions, concerns, recommendations, or criticisms in the comments section. This motivates me to keep improving and writing on dev

See you later! ❤️

Read More:

[7 JavaScript clean coding tips every developer should know 😎
](https://dev.to/braincuber_technologies/7-javascript-clean-coding-tips-every-developer-should-know-3pno
)

[Top JavaScript VSCode Extensions for Faster Development 🔥
](https://dev.to/braincuber_technologies/top-javascript-vscode-extensions-for-faster-development-597k)
Some More Notes on Asahi Linux - 02
Tags: linux
Published: 2022-04-26 05:00:56

I got the ethernet adapter and voila! It worked immediately. I installed the dialog package and then used wifi-menu which seemed to throw an error when I connected to my home network but I found that I was already connected to the wifi.

It looks like my wifi profile that I wrote under /etc/netctl/my_profile was already working.

This is the command I used to update the pacman package manager. This seems to be the same as doing apt-get update.

```
$ pacman -Syu
```

I also had to install the wpa_supplicant package. 

Once I got wifi working, I disconnected the ethernet adapter and installed X and i3-gaps. This was pretty straightforward. Xterm wasn't appearing because the xorg-xmessage package was missing. I only found this out when I ran xterm in the shell which was a bit annoying. It'd be nice to have a terminal window that would output what X is doing.

The biggest issue that I have now is that my terminal text is tiny. I changed the dpi of X which helped quite a bit but my terminal is still screwy. Not sure if I want to deal with it or just install a different terminal.

Firefox is also ugly as sin. I forgot how bland it looks. I really want the polish level of macos but I also don't if that makes sense.

Oh well! I installed dmenu as which is something I love that I forgot about. Also installed sudo.

I'll need to get my vpn connection to work working as I do plan on doing some work when I go to Italy.

I switched my terminal to kitty and that worked out of the box with the dpi setting I'm using. With my terminal and wifi working, and firefox not looking as bad now that I lowered the dpi to 144, I think my asahi linux install is pretty easy to use now. I've installed a whole slew of things, the biggest thing being vim and fish. I realllly want a bash shell with fish capabilities.

I also use the starship prompt but I could probably do without it. 

I really like using three fingers to paste.

At this point I'd consider my asahi linux set up pretty much done. Luckily I didn't run into too many issues. The guys who got this working so easily are insane.

Used feh to add a background, added it to the i3 config so it loads when I start. The next step is add taskbar as I would like a dock of some sort.

Installed rust, Goddamn is it significantly faster. My PC is a gaming rig but wsl2 took 1.88s vs mac's 0.16s. Something must be wrong. I'll need to check if my windows version is doing something wacky.
Create a header that appears and disappears by scrolling
Tags: design, javascript, webdev
Published: 2022-04-27 08:01:00

---
title: Create a header that appears and disappears by scrolling
published: true
date: 2022-04-26 05:00:00 UTC
tags: design,javascript,webdev
canonical_url: https://akimon658.github.io/en/p/2022/awesome-header/
---

Headers can be animated easily by CSS and a few JavaScript, but the speed will be constant. I hate that, so I’ll create a header that works naturally like this.

![Search result screen of Google images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i90yyaberzvl9wpq21ta.gif)

## Sample code & Demo

{% codepen https://codepen.io/akimon658/pen/zYpROeV %}

This script changes the value of `top` by scrolling.

```javascript
const header = document.querySelector("header"),
  headerStyle = window.getComputedStyle(header),
  headerHeight = parseFloat(headerStyle.height);

let lastPosition = 0;

document.addEventListener("scroll", () => {
  const currentPosition = window.scrollY,
    diff = currentPosition - lastPosition;

  let newTop = parseFloat(headerStyle.top) - diff;
  if (diff < 0) {
    newTop = Math.min(newTop, 0);
  } else {
    newTop = Math.max(newTop, 0 - headerHeight);
  }

  header.style.top = `${newTop}px`;
  lastPosition = currentPosition;
});
```

If your header has a shadow, you also need to calculate that.

```javascript
newTop = Math.max(newTop, 0 - headerHeight - shadowHeight)
```
📅 The Most Efficient Self-Taught Learning is Routine
Tags: beginners, productivity, career
Published: 2022-04-26 03:27:58

I love to learn, but I hate finding time for it.

We all only have 24 hours in a day. Between work, sleep, and everything else, you're probably juggling a lot already! The challenge for anyone doing self-taught learning is finding out how much time you can set aside **consistently** — fitting it into your regular routine, the cadence of your daily life.

Taking two hours to dive into something every other Saturday is a great supplement to your regular cadence. But if that's all you can do, you're gonna spend a good chunk of each time block just trying to remember where you left off.

If you can set aside even a half hour every weekday, or even just three days a week, you will feel the progress. And any big blocks of time you *can* snag will be infinitely more productive!

Fair warning that, best case, you'll be taking this time from your solo free time. Yes, that still sucks. But it's still better than depriving yourself of sleep, or neglecting your relationships.

It's common for people trying to learn new skills to be drained by the time they get time for it. I found a way around this in my schedule by doing it first thing in the morning, before I hop into any other work. This works for me because I'm already awake a couple hours before my job typically starts.

Everyone's schedule is different. As long as you're making the time and protecting it wherever it lands on your schedule, you're moving forward along your path. It doesn't have to be a huge long session each time, and it doesn't even have to be every day. It just needs to be **consistent**!
Building and agile mindset and leaving the comfort zone
Published: 2022-04-26 03:24:33


Technology is in constant evolution, everyday new products are built, software updates, framework versions. But we already know that, how do we take the advantage? 

Working on leaving our comfort zone and being open to learn new things is going to help us on building an agile mindset, a good example as a developer would be start learning  a new programming language.  This will help us to be more analytic and be capable of solve any problem without depending on a specific solution. 

And agile mindset will also help us to improve our communication skills making  posible working better as a team.
This week I started implementing this strategy. As frontend developer I've been working with javascript for a year but I decided to leave my comfort zone and started learning Ruby. Things are very different between programming languages but at the end of the day the logic is the same. 

We need to focus on building and agile mindset and implementing this in many other areas.
#Hello, World!
Tags: beginners, javascript, css, html
Published: 2022-04-26 03:19:52

Not only am I new to blogging, but also completely new to coding in general. I'm currently enrolled in Flatiron school for their Software Engineer program and today is my first day! In their course they mention blogging is a good way to help myself learn and see my progression and though I was a bit skeptical at first, since I've never written a blog before in my life, and the fact that I know little coding, like every other life challenge I might as well try and give it my all because what's the worst that can come out of it! Hopefully you all see my progress throughout my journey to becoming a software engineer and in turn, hopefully I help some of you with tips and tricks I learn throughout my time with Flatiron. So as they say when first learning to code, "Hello, World!".
JavaScript Interview questions
Tags: javascript, webdev, interviewquestion, react
Published: 2022-04-26 02:50:25

The blog is regarding popular and unique interview question which I come across during interview or from other candidates.
This might include tech stack of web dev related to Vanilla Javascript majourly and also include React js, Node js, TypeScript, Angular, HTML and CSS

Lets go!!!


 ->  Java Script
1) Event bubbling and event capturing and event delegation 
    sol: Event delegation refers to the process of using event 
         propagation (bubbling) to handle events at a higher level 
         in the DOM than the element on which the event originated

2) Function Borrowing =>  call , apply, bind => create your own call, apply, bind prototype
3) Create your own map in js
4) strict mode
5) inspect tab
6) create your own Flat method 
7) Object.is() vs === vs ==
8) type of Nan and Number.Nan


-> React js
1) control component and uncontrol components
2)  create your own custom hook
3) diff usememo , usecallback and memo 
4) side effect in react
5) React Virtualisation
6) React fiber
7) diffing reconcilation
8) useref and memoisation
9) bundle.js
10) suspense , server render

-> CSS
1) Create elipsis (Hi i am ...)
2) Create a Clock with js and css like actual non digital clocks with minutes and hour hand ticking
SQL-Quick tip #10 - Select table definition
Tags: tsql, sqlserver, sql, mssq
Published: 2022-04-26 02:32:25

## Sql Server tips and tricks

This is part of a series of quick tips and tricks I have accumulated over the year, that I think can be useful for others.
If you have similar short tips and tricks please leave a comment.

### Select table definition

Have you ever had the task of documenting a whole database or maybe just a few tables some programmer created years ago. I have, and I quickly found that having a query to directly select the schema of a table was a huge timesaver.
Or maybe you don't have access to the production database, but the bugs or performance issues you experience, indicate a missing index or a wrong column definition, so you need to send a request for the IT operations department to fetch the information about a table from the database for you.
In both cases the queries below can be very useful.

```sql
DECLARE @tableName VARCHAR(100) = 'Customers'

SELECT table_name, ordinal_position, column_name, data_type, character_maximum_length, is_nullable
  FROM information_schema.columns
 WHERE table_name = @tableName

SELECT table_name, constraint_name
  FROM information_schema.constraint_table_usage
 WHERE table_name = @tableName

SELECT name, type_desc, is_unique, is_primary_key
  FROM sys.indexes
 WHERE object_id = OBJECT_ID(@tableName)
```

![Sql Server Management Studio screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eg6u7md4u1eo9mvn0v3t.png)
Passing pre-computed routes to link-to helper in Ember
Tags: ember
Published: 2022-04-26 02:21:49

**Syntax**

```html
{{link-to routeName  dynamicSegment1 dynamicSegment2 (query-params key1=value1 key2=value2)}}

(or)

{{link-to params=linkParameters}}
```

**Description**

Consider a photo application with below routes
```js
this.route('photos', function() {
  this.route('resolution', {
    path: '/:value'
  });
});
```

Compute links in component
```js
linkParametersVariation1: computed({
  get() {
    let resolution = get(this, 'resolution);
    return { 'routeName': 'photos/resolution', dynamicSegment: resolution, page: 1, perPage: 30 }
  }
}),

linkParametersVariation2: computed({
  get() {
    let resolution = get(this, 'resolution);
    return ['photos/resolution', resolution, { isQueryParams: true, values: { page: 1, perPage: 30 } }]
  }
})
```

Using links in template
```html
{{#link-to linkParametersVariation1.routName linkParametersVariation1.dynamicSegment (query-params page=linkParametersVariation1.page perPage=linkParametersVariation1.perPage)}}
  <div>variation1</div>
{{/link-to}}

{{#link-to params=linkParametersVariation2}}
  <div>variation2</div>
{{/link-to}}
```
Difference between controlled components and uncontrolled components in Reactjs
Tags: react, beginners
Published: 2022-04-26 01:30:49

---
title: Difference between controlled components and  uncontrolled components in Reactjs
published: true
description: 
tags: #reactjs #beginners
//cover_image: https://direct_url_to_image.jpg
---
## I - **Controlled components**

In controlled components, the form data is handled by React components, and it is recommended to use controlled components to implement forms.

Example:

```
import React, { useState } from 'react'

export default function ControlComponent() {
  const [state, setState] = useState({
    value: ''
    })

    const handleChange =(event)=> {
      setState({value: event.target.value});
     }

    const handleSubmit = (event)=> {
    alert('A name was submitted: ' + state.value);
    event.preventDefault();
    }

    return (
    <form onSubmit={handleSubmit}>
            <label>
              Name:
              <input type="text" value={state.value} onChange={handleChange} />
            </label>
            <input type="submit" value="Submit" />
          </form>
    );

}
```

## II- **Uncontrolled components**

In uncontrolled components, the form data is handled by the DOM itself.
Instead of writing an event handler for every state update, you can use **useRef** to get form values from the DOM.

Example:
```
import React, {useRef} from 'react'

export default function UnControlledComponent() {
  const inputElement = useRef(null);

  const handleSubmit =(event)=> {
     alert('A name was submitted: ' + inputElement.current.value);
     event.preventDefault();
   }

     return (
       <form onSubmit={handleSubmit}>
         <label>
           Name:
           <input type="text" ref={inputElement} />
         </label>
         <input type="submit" value="Submit" />
       </form>
     );
}

```
Progressive Web App (PWA): The Definitive Guide
Tags: webapp, coredna, pdf, pwa
Published: 2022-04-26 01:21:51

If you’re ready to know everything you need to know about Progressive web apps, it's what it is, it's workings, pros and cons... Then look no further! 

In this guide, you'll learn:

- What is a Progressive Web App (PWA)?
- Progressive Web App attributes
- PWAs vs. responsive websites
- PWAs vs. native apps
- How does a Progressive Web App (PWA) work?
- The benefits of a Progressive Web App
- And many more

Check it out [here!](https://bit.ly/3MMCVNh)
Como evitar SQL Injection no MongoDB
Tags: nestjs, mongodb, typescript, codaql
Published: 2022-04-26 01:09:27

**O que é SQL Injection?**

_SQL Injection é um ataque no qual código malicioso é passado para um servidor SQL, que o executa. O ataque pode resultar em acesso não autorizado a dados confidenciais, ou destruição de dados críticos._

Como saber se uma query não previne SQL Injection?!

Neste exemplo estou usando CodeQL, o que é CodeQL?!

- É um mecanismo de análise de código que descobre vulnerabilidades.

Nesse exemplo na aba de security do github:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehs5k1nb7orvw8ius963.png)

_O code sacanner nos avisa, que se uma consulta de banco de dados (como uma consulta SQL ou NoSQL) for criada a partir de dados fornecidos pelo usuário sem higienização suficiente, um usuário mal-intencionado poderá executar consultas de banco de dados mal-intencionadas._

Como recomendação para queries NoSQL, podemos usar um operador como `$eq` do MongoDB

Iremos fazer um refactor no UsersRepository para evitar SQL Injection:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6v711myd0am4vpspv9m.png)

Depois de rodar o Github Actions, notamos que não tem mais alerta na aba de security no github:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s3vgbwux6gtgtzghzn0.png)

E assim não temos mais alerta de SQL Injection;

Repo de exemplo:

https://github.com/williamkoller/my-readings

Espero ter te ajudado de alguma maneira, pode comentar e compartilhar.
How can I get the client ID and client secret from my Keycloak installation to use it in my web app for authentification?
Tags: keycloak, java
Published: 2022-04-26 01:08:59

---
title: How can I get the client ID and client secret from my Keycloak installation to use it in my web app for authentification?
published: true
description: 
tags: keycloak, java
//cover_image: https://direct_url_to_image.jpg
---
How to Add Okta Authentication to a Java Application
Tags: java, webdev, cybersecurity
Published: 2022-04-26 00:32:05

Do you want to learn how to add Okta authentication to your Java application without writing code? In this step-by-step tutorial, you will learn how to integrate a Java application with Okta using Datawiza to implement OIDC/OAuth SSO authentication in 5 mins. 

## The benefits of using Datawiza

- No need to learn complex OIDC/OAuth or SAML protocols
- No need to manage refresh tokens, access tokens or ID tokens
- No need to manage user sessions
- No need to use SDKs, call APIs or write code
- Reduce weeks of engineering work to hours, even minutes
- Avoid security vulnerabilities with a No-Code product developed by security experts

Ready to see how easy it is?  Let’s get started!

[Learn more...
](https://www.datawiza.com/blog/technical/okta-authentication-java-application/)
React Tricks Miniseries: Series Intro
Tags: react, javascript, webdev, theeasydev
Published: 2022-04-26 00:07:07

Hey Devs!

Welcome to my new Mini-Rapid Series on React How To's!

In this brand new series i will be posting once or twice a day a useful brief guide or trick on how to solve a common problem in React JS. 

I'll be sharing some cool stuff i have learned in React over the past 6 years. So be sure to stay tuned and follow my posts and follow the tag _#theEasyDev_.

I hope you will learn react in a quick and fun way with this miniseries.

All post will highly encourage feedback and discussion so don't be shy and comment if you would like to add something interesting.

Easy out!

The Easy Dev
Creating Flipable Card Using HTML/CSS/JS
Tags: javascript, webdev, html, css
Published: 2022-04-25 23:02:30

You can create flipable card easily by tracking these steps.

HTML file:

```html
<div class="wordCard">
    <div class="cardFace frontFace">
        <span>front</span>
    </div>
    <div class="cardFace backFace">
        <span>back</span>
    </div>
</div>
```

CSS file:

```css
.wordCard {
    width: 200px;
    height: 300px;
    position: relative;
    perspective: 1000px;
    cursor: pointer;
}

.cardFace {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    color: white;
    width: 100%;
    height: 100%;
    border-radius: 10px;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    transition: transform .5s linear;
    transform-style: preserve-3d;
}

.backFace {
    background-color: blue;
    transform: rotateY(180deg);
}

.frontFace {
    background-color: green;
    transform: rotateY(0deg);
}

.flipped .backFace {
    transform: rotateY(360deg);
}

.flipped .frontFace {
    transform: rotateY(180deg);
}
```

We have two type faces. Normal and flipped faces.

Our important property is `backface-visibilty: hidden;`. This property helps us to hide back face of element.

Other important property is `transform-style: preserve-3d;`. This property gives 3D rotate effect to element when it is rotating.

And JavaScript file:

```js
var card = document.querySelector('.wordCard');
card.addEventListener('click', () => {
    card.classList.toggle('flipped');
});
```
In above, we set `click` event to toggle `.wordCard` class. In this way, we could animate this card with transition duration.
Revisiting Mastodon for Devs
Tags: webdev, programming, socialmedia, mastodon
Published: 2022-04-25 22:30:46

There was a thread about Mastodon instances for devs back in 2018 but at least one of the mentioned servers (toot.cafe) seems to not be a thing anymore. Is mastodon.technology the place for front-end, back-end, full-stack folks or are there better choices?
Lunes de música... ¿Qué estás escuchando? 🎵
Tags: spanish, music, discuss, monday
Published: 2022-04-25 22:23:54

> **"Sin música, la vida sería un error."**
_Friedrich Nietzsche_

La música es parte importante de la vida de la mayoría de las personas y una vida no basta para poder escuchar todas las canciones que quisiéramos o conocer a todos los artistas, solistas o bandas.

Últimamente mis gustos musicales han sido muy estáticos y siento que necesito abrir mis horizontes y poder conocer nueva música interesante. 

Este post será la primera entrega de una serie semanal que lanzaré todos los lunes para que como comunidad podamos compartir y por qué no conocer nuevas melodías. 🎶

Puedes compartir tus sugerencias usando los *liquid tags* de Dev.to, por ejemplo:

* Para compartir un video desde youtube:
```js
{% youtube dQw4w9WgXcQ %} // dQw4w9WgXcQ es el id del video
```

* Para compartir una canción desde spotify:
```js
{% spotify https://open.spotify.com/track/2xcuDxTLlp0ro2GYlS1i9G?si=914e659148f44d4c %} 
```

Mi sugerencia para esta semana es un tema de mi banda de rock alternativo francesa favorita, **Mickey 3D**
 
{% spotify https://open.spotify.com/track/2xcuDxTLlp0ro2GYlS1i9G?si=66beeca4ce6f41db %} 

---

Este post no sería posible sin mi amigo @michaeltharrington y su post:

{% link https://dev.to/michaeltharrington/music-monday-what-are-you-listening-to-4g1o %}

Los respectivos créditos a él por ser tan buena onda. 

Y dime, ¿qué estás escuchando ahora? Te leo en los comentarios.