teleren/devto huggingface dataset:
😲10 JavaScript Concepts Every Developer Should Know
Tags: 100daysofcode, javascript, codenewbie, programming
Published: 2022-07-29 17:21:00

Hey guys, 

In this article, let us see the 10 concepts that you as a developer must know. 

Now before starting, if you want to learn JavaScript from the absolute scratch, consider going through my **10 JavaScript Projects** for learning JavaScript. In this video, we create 10 small and medium but different projects for learning the language. Here is the link of the video just in case if you want to check that out : 

{% youtube KTGfHmyje5A %}

## 1. Immediately Invoked Function Expressions
 

{% youtube Px6dxZa6DQ4 %}

## 2. Constructor Functions and Prototypal Concept 

{% youtube -0IMVvIJcvU %}

## 3. The Event Loop, Call Stack and Message Queue 

{% youtube vCS3D2j-B_U %}

## 4. Event Capturing, Bubbling and Delegation 

{% youtube OhvACESHThQ %}

## 5. Understanding Promises and Error Handling 

{% youtube 90ML5WL5BLY %}

## 6. Promise.all, Promise.race and Promise.allSettled methods

{% youtube yVwukhqoThg %}

## 7. Async Await - Deep Dive 

{% youtube m-dsODVzQHo %}

## 8. Iterators in JavaScript 

{% youtube 2N9Hy7PWo-s %}

## 9. Hoisting in JavaScript 

{% youtube XPNk2oAB2oM %}

## 10. Understanding Closures  

{% youtube UUt4NZWEWr8 %}



--- 
Support my channel:
💜 Join the Discord community 👨‍👩‍👧‍👦: https://discord.gg/fgbtN2a 
💜 One time donations via PayPal
Thank you! 🙏

---
Follow me on:
👉 My Blog: https://the-nerdy-dev.com
👉 Twitter: https://twitter.com/The_Nerdy_Dev
👉 Instagram: https://instagram.com/thenerdydev
New Partnership Opportunity. Help Needed
Tags: javascript, blockchain, webdev, beginners
Published: 2022-07-29 17:11:13

Hello, I am a project manager working on a small project which may lead to larger projects later but for now I am trying to have a Monero and Elctroneum application that mines coins. My goal is to use the application for our own mining needs and to also sell copies of the software. I am looking for potential partners or developers who might want to join the project or offer a quote for their services to build this project. I have a marketing partner who will help market the software. I need to have the system built now and wanted to put this post up in hopes of finding a partner or a dev who could help. I have some libraries off of NPM and Libraries.io from which I believe would do the trick here. It should not be to hard of a build. If you have any experience with Monero or Electroneum that would be a big plus. Thank you for reading this post and please contact me through Dev.to for further information. Thank you!
⚡Tidbits of Virtual DOM Explained
Tags: 100daysofcode, react, programming, codenewbie
Published: 2022-07-29 17:06:20

Hi, 

I recently wrote an article explaining the Virtual DOM in great detail. Go check that out here : 

**https://the-nerdy-dev.com/demystifying-virtual-dom-in-react-js/**

Also I do have a video explaining the same just in case if you prefer visual content instead of an article. 

{% youtube L2-GO6SVqNU %}

Also check this article : 

{% embed https://dev.to/prateek951/10-javascript-projects-every-beginner-should-build-23c2 %}

--- 
Support my channel:
💜 Join the Discord community 👨‍👩‍👧‍👦: https://discord.gg/fgbtN2a 
💜 One time donations via PayPal
Thank you! 🙏

---
Follow me on:
👉 My Blog: https://the-nerdy-dev.com
👉 Twitter: https://twitter.com/The_Nerdy_Dev
👉 Instagram: https://instagram.com/thenerdydev
Storyblok Gatsby SDK – now with TypeScript support 🎉
Published: 2022-07-29 16:55:15

During this summer, we have been working on to support TypeScript in our SDK ecosystem.
We have TypeScript for [@storyblok/js](https://github.com/storyblok/storyblok-js) SDK, [@storyblok/svelte](https://github.com/storyblok/storyblok-svelte) SDK, [@storyblok/vue](https://github.com/storyblok/storyblok-vue) & [@storyblok/vue-2](https://github.com/storyblok/storyblok-vue-2) SDK, [@storyblok/react](https://github.com/storyblok/storyblok-react) SDK... and finally, [gatsby-source-storyblok](https://github.com/storyblok/gatsby-source-storyblok) (Gatsby SDK) also supports TypeScript👏

Now, you can add typing to your Gatsby projects, while having an even better developer experience connecting to Storyblok.

Can't wait to test it out? You can try it out from our [Gatsby boilerplate repo](https://github.com/storyblok/gatsby-storyblok-boilerplate/tree/feature/typescript-support)!

If you install [gatsby-source-storyblok](https://github.com/storyblok/gatsby-source-storyblok) newly or update it into v4.1.0, you'll be able to enjoy auto-completion, static typing and warnings in case something doesn’t add up, even if you are not using TypeScript🕵️‍♀️


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

If you'd like to know more details about Gatsby and TypeScript, Gatsby provides a [full documentation](https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/) how you can configure and use it from zero to hero.

Also, if you want to learn how to integrate Storyblok into your Gatsby project, you can follow our [5 minutes guide](https://www.storyblok.com/tp/add-a-headless-cms-to-gatsby-5-minutes) to implementing Gatsby with Storyblok.

As a wrap-up, I'd like to say a special thanks to [Alex Jover](https://twitter.com/alexjoverm) for giving me many new knowledge as well as [Josefine](https://twitter.com/JsfnSchfr), [Facundo](https://twitter.com/facundozurdo) and [Manuel](https://twitter.com/manuschroeder) for working together in a SDK squad💪

Lastly, we'd love to hear your experience and feedback. Feel free to share with us how's your experience with our SDKs and we're open to hear your ideas to keep improving our SDKs.

Let's make our SDKs better together through community!
VSCode: Changing Font Size
Tags: vscode, font, size, change
Published: 2022-07-29 16:50:08

You can change the font size in VSCode by going to the "File" menu, clicking on "Preferences", and then selecting "Settings". In the settings window, under the "Editor" tab, you will find the "Font Size" option.

You can use the up and down arrows to increase or decrease the font size. You can also type in a specific font size if you want. Once you have made your changes, click on the "OK" button to save them.

If you want to change the size of the VSCode UI frame, you can go to the "View" menu and click on "Appearance". In the appearance window, under the "Window Controls" section, you will find the "Resize Window" option.

You can use the up and down arrows to increase or decrease the size of the UI frame. Once you have made your changes, click on the "OK" button to save them.

To change the color theme in VSCode, go to the "File" menu and click on "Preferences". In the settings window, under the "Workbench" tab, you will find the "Color Theme" option.

Select the color theme that you want from the drop-down menu and click on the "OK" button to save your changes.

Oh and for visual learners...

{% embed https://www.youtube.com/watch?v=kCUoqQNy1jc %}

Check out Semicolon's 2-minute VSCode tutorial showing visually [how to change font size in vscode](https://www.youtube.com/watch?v=kCUoqQNy1jc) 🙂
Namespaced errors for Ruby
Tags: ruby, errors, exceptions
Published: 2022-07-29 16:06:12

---
title: Namespaced errors for Ruby
published: true
description: Errors are part of the API, treat them right
tags: Ruby, errors, exceptions
cover_image: https://i.postimg.cc/xT6Wmh2x/alexander-hipp-5t-Iu-YKRRHj8-unsplash.jpg
---

Today I was working on upgrading the version of Dentaku gem we use for resolving user-provided, untrusted formula inputs.

I was able to observe an interesting evolution of how error classes are treated in the gem:
1. [A naive implementation](https://github.com/rubysolo/dentaku/blob/2f0744dc9ccdf816b058bf77e510870af3fdf607/lib/dentaku/exceptions.rb) - there's just one custom error and most of the API relies on built-in errors like `RuntimeError` and `ArgumentError`. Needless to say, this is a poor showing, problems will be hard to debug.
2. [Next step in the evolution](https://github.com/rubysolo/dentaku/blob/082ffb989c2f484a02c9f7448e1a1ea89c43aabd/lib/dentaku/exceptions.rb) - some more custom errors get defined for common failure spots. Debugging is improved.
3. [Final form](https://github.com/rubysolo/dentaku/blob/e0b605456cc663c5d2a61b01f8df897125387740/lib/dentaku/exceptions.rb)? A rich set of errors is defined, and, most importantly, all gem's errors inherit from `Dentaku::Error` base class, allowing simple catch-all rescues in using code:

```rb
def my_method
  Dentaku(my_formula)
rescue Dentaku::Error # will handle Dentaku::ParseError, Dentaku::TokenizerError etc. 
  warn_user("Something is incorrect in the formula")
end
```

## The takeaway

When working on a gem or even a component in a larger system, treat errors as 1st class API citizens, alongside inputs and outputs. Document them and apply good software architecture principles. Have a way to expose any raised errors in method docs, as well as having a glossary of all errors possible in the code.

Distilling Dentaku's approach we get this file structure:

```
dentaku/
  lib/    
    dentaku/
      exceptions.rb
    dentaku.rb
```

And zooming in on what exactly goes on in `exceptions.rb`:

```rb
module Dentaku
  # The "abstract" toplevel parent error class for all errors
  # raised by this gem, allows users to do
  # `rescue Dentaku::Error` in their code for a catch-all solution.
  # Also gives an opportunity to have all errors inside the 
  # gem have the same API, some metadata etc. depending on 
  # whether this is needed for the domain of the system.
  class Error < StandardError; end 

  # A "concrete" error class for the gem.
  # -- Description when this error is raised and possible solutions/changes needed to avoid it --  
  class ParseError < Error
  end
end
```

Photo by <a href="https://unsplash.com/@alexanderhipp?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Alexander Hipp</a> on <a href="https://unsplash.com/s/photos/cascade?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Code Smell 153 - Too Long Names
Tags: javascript, webdev, beginners, programming
Published: 2022-07-29 16:04:51

*Names should be long and descriptive. How Long?*

> TL;DR: Names should be long enough. No longer.

# Problems

- Readability

- Cognitive Load

# Solutions

1. Use names related to the [MAPPER](https://dev.to/mcsee/what-is-wrong-with-software-5pa)

# Context

We used [very short names](https://dev.to/mcsee/code-smell-33-abbreviations-356o) during the 50s and 60s due to space and time constraints.

This is no longer the case in modern languages.

Sometimes we get too excited.

Naming is an art and we should be cautious with it.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/661d68a82e80799c6f9330d33c271a0b)
```java
PlanetarySystem.PlanetarySystemCentralStarCatalogEntry

// Redundant
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/7da772566dee2fb79f3bfea13196ee22)
```java
PlanetarySystem.CentralStarCatalogEntry
```

# Detection

[X] Semi-Automatic 

Our linters can warn us with too long names.

# Tags

- Bloaters

- Naming

# Conclusion

There are no [hard rules](https://dev.to/mcsee/what-exactly-is-a-name-part-i-the-quest-61k) on name length.

Just Heuristics.

# Relations

{% post https://dev.to/mcsee/code-smell-33-abbreviations-356o %}

# More Info

- [What exactly is a name? — Part I: The Quest](https://dev.to/mcsee/what-exactly-is-a-name-part-i-the-quest-61k)

- [What exactly is a name? — Part II: Rehab](https://dev.to/mcsee/what-exactly-is-a-name-part-ii-rehab-20gd)

- [Long and Short of Naming](https://agileotter.blogspot.com/2009/08/long-and-short-of-naming.html)

# Credits

Photo by [Emre Karataş](https://unsplash.com/@emrekaratas) on [Unsplash](https://unsplash.com/s/photos/long)
  
* * *

> Many people tend to look at programming styles and languages like religions: if you belong to one, you cannot belong to others. But this analogy is another fallacy.

_Niklaus Wirth_

{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
How to remember the ways of rounding a number to an integer?
Published: 2022-07-29 16:00:27

---
title: How to remember the ways of rounding a number to an integer?
published: true
description: 
tags: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sf8tlr9b1kz217cetsng.jpg
# Use a ratio of 100:42 for best results.
---

There are 4 methods of the global **Math** object, which are used for rounding numbers to an integer: `Math.floor()`, `Math.ceil()`, `Math.round()` and `Math.trunc()`

The article provides visual examples for better memorization. Let's start with the most _(in my opinion)_ logical ones: `Math.floor()` and `Math.ceil()` which have very descriptive names. The meaning of these words already gives us a huge clue for remembering the way each method works.

**Math.floor()** - rounds to a smaller integer number. It means, that we always press the number to the floor.

![Math floor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2ukjo48gbtlb6kqdsjl.png)

**Math.ceil()** - rounds to a larger number. 
We pull the number to the ceiling.

![Math ceil](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqnwff457nxy9dotuvzm.png)

In everyday life, we are used to round numbers based on the proximity of a fractional value to the whole. Proximity for us is determined by half of the number. That is, if the fractional value of the number has exceeded 0.5, then we can say that it is about 1. Half in our case is a barrier that can be used to round up a number to a larger one.

Just for this more humanly correct rounding, JS has the next tool for rounding numbers **Math.round()**.

![Math round](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqxbjq0x3ejhg79e9d59.png)

But pay special attention to the negative and positive half. If we have reached exactly half the positive number, then we will round the number to the next larger number on the scale to the right. We will also do the same with a negative number. We will round it to a larger number. `Math.round(-2.5) // -2`. That is, seeing half of our number we will move to the right (to a larger number).

And the last, incredibly easy to understand method: **Math.trunc()**. The method simply returns an integer, discarding the fractional part. You can simply imagine that the number is not rounded, but loses its fractional part and you will not be mistaken.

![Math trunc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1a91nvjbw63v7rgqyn9i.png)

`Math.trunc()` does not work in browsers prior to `IE10`. But there is a very easy polyfill. 

```js
if (!Math.trunc) {
  Math.trunc = function(v) {
    v = +v;
    return (v - v % 1)  (!isFinite(v)  v === 0 ? v : v < 0 ? -0 : 0);
  };
}
```

You can also use the prototype methods of `Number`: `toFixed()` and `toPrecision()`, but remember that these are not methods of the built-in `Math` object and they return a string, not a number.
The Benefits of Using Microservices for Edge Devices - Luos
Tags: opensource, microservices, embedded, luos
Published: 2022-07-29 15:54:35

We recently wrote an article about the benefits of using microservices for edge devices in The New Stack.

⏩ https://thenewstack.io/the-benefits-of-using-microservices-for-edge-devices/

We believe that electronic design should be “microservice-able” and are working on an opensource library (luos) that helps separate code into services so that it is easy to integrate and maintain into a project.
Elixir script, what can and can't be done
Tags: elixir, script, exs, examples
Published: 2022-07-29 15:53:51

Outside of `mix.exs` I haven't engaged with `.exs` files much. I imagine that might be the same for some of you. However,  I ran into a situation recently where I needed to.

I wanted my elixir project in a docker container, so that when running it would go straight into the terminal awaiting user input; collect the input line by line and return a list of all of those lines when an empty line is given. Creating an elixir script as the `ENTRYPOINT` for the program felt like the right thing to do. However, I struggled to find any substantial documentation and/or examples to understand the limitations of _what can and cannot be done with elixir script_.

After some trial and error, I found some bits that worked and started iterating from there until I had something I could use for my project. What follows are examples of where the code does the same thing but in different formats and layouts. Side note, for code snippets from the terminal, I've named the file `start.exs`  

Also, we get to have a look at `IO.stream` ([docs](https://hexdocs.pm/elixir/1.12/IO.html#stream/2)) for anyone else that might have ran into the same issue as me.

## You can define functions!
In hindsight (which is always 20/20) this makes sense but for whatever reason it didn't occur to me that you can do this. The only difference here compared to a normal elixir module is that you call the function at the end of the file.

```elixir
defmodule Lines do
  def run(lines \\ []) do
    case IO.read(:stdio, :line) do
      "\n" ->
        # done reading lines!
        lines
        |> Enum.reverse()
        |> Enum.map(&String.replace(&1, "\n", ""))
        |> IO.inspect()

      line ->
        run([line | lines])
    end
  end
end

Lines.run()
```

```bash
$ elixir start.exs
hi
there

["hi", "there"]
```

## No thanks, I prefer my functions anonymous.
Here's another approach, if for whatever reason you didn't want to define modules or functions.

```elixir
IO.stream(:stdio, :line)
|> Enum.reduce_while([], fn line, lines ->
  case line do
    "\n" -> {:halt, lines |> Enum.reverse()}
    line -> {:cont, [line | lines]}
  end
end)
|> Enum.map(&String.replace(&1, "\n", ""))
|> IO.inspect()
```
```bash
$ elixir start.exs
hi
there

["hi", "there"]
```
## Time for my final form
```elixir
IO.stream(:stdio, :line)
|> Enum.take_while(&(&1 != "\n"))
|> Enum.map(&String.replace(&1, "\n", ""))
|> IO.inspect()
```
```bash
$ elixir start.exs
hi
there

["hi", "there"]
```

---

## Conclusion
The point of this article, wasn't so much the code but I think I struggled to get my head around scoping issues after only ever dealing with _traditional_ elixir code. Hopefully, if you're in a similar situation, you can now see that there is more flexibility than you might have originally thought.

In regards to `IO.stream` docs. I made [a PR](https://github.com/elixir-lang/elixir/pull/12031) to make some amendments.
Building React Frontends Without Waiting for an API
Tags: react, javascript, webdev
Published: 2022-07-29 15:51:00

There's a good chance you've been in _this_ situation as a frontend developer: you've been tasked with building a shiny new feature, but the API endpoints you need have not yet been created.

Whilst it is possible to emulate intended behaviour - wiring up API endpoints later on is usually cumbersome and unappealing.

## Mock Service Worker to the Rescue!
MSW is a library that can mock API endpoints at the **network level**. This means we can build components as if API endpoints **already exist**, with our app and browser not knowing any different.

Add MSW to your project
```
yarn add msw --dev
```

Use the CLI to add the service worker to your server's public folder. In this example I am using Create React App.
```
npx msw init public/ --save
```

Define handlers and setup the worker. Here we are telling MSW to mock a GET request to `/user`, responding with an object containing `username: admin`.
```javascript
// src/mocks/browser.js
import {rest, setupWorker} from 'msw'

const handlers = [
    rest.get('/user', (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json({
                username: 'admin',
            }),
        )
    }),
]

export const worker = setupWorker(...handlers)
```
Start the worker with your app
```javascript
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

if (process.env.NODE_ENV === 'development') {
    const { worker } = require('./mocks/browser')
    worker.start()
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
```

Now when starting your app, you should see the message "**[MSW] Mocking enabled**" in the browser console; meaning we are good to go!

## Using our mocked data
Let's create a basic component that can use our newly mocked endpoint.

Define state to store our username
```javascript
const [username, setUsername] = useState();
```

Add a fetch call on component mount
```javascript
const fetchUser = async () => {
    const response = await fetch('/user');
    const data = await response.json();
    setUsername(data.username);
}

useEffect(() => {
    fetchUser().catch(console.error);
},[])
```

If we have the username defined in state, return a greeting, otherwise return a loading message.
```javascript
if(username){
    return <h1>{`Hello, ${username}!`}</h1>
}

return "Loading..."
```

You should now see this when running your app:

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

Hopefully this basic example shows the ease of integrating MSW into React apps, and how it reduces dependency on others whilst developing.
Clock Time, Event Time, and TimeSignalMe
Tags: laravel, php, time, remotework
Published: 2022-07-29 15:32:10

## Clock Time and Event Time

People have two distinct concepts of time, clock time, as signaled by the hour, and event time, a time block reserved for an event, such as brainstorming. Both are useful, but in different circumstances during a day of work.

For a more detailed discussion of the concepts, including references to research, see David Kadavy's article [Are You on ‘Clock Time’ or ‘Event Time?’](https://forge.medium.com/are-you-on-clock-time-or-event-time-bee45818c171). 

## TimeSignalMe 

*TimeSignalMe* is a web application incorporating both concepts of time to be shared across a group. 

A group sharing a time signal can work with a clock or an event time for productive work. 

Using a shared time block for meetings or brainstorming is quite common, that is, sharing Event Time. In contrast, we seldom share Clock Time. We believe this ignores the multi-faceted nature of the shared time sense of a group. 

With in-person work, hybrid work, and remote work, we all need a shared sense of time, both Clock Time and Event Time. Yes, even if we are all in the same place, each at their desk, we still need to feel the time passing in the shared sense.

## Sessions

Users start a group session, within which they can run a single Clock Time process and multiple Event Time processes. 

The user can then invite other users to the session via a link so that other users can join the session via their email. 

## Implementation Sketch

This application fits the TALL stack - [Laravel](https://laravel.com), Livewire(https://laravel-livewire.com), Alpine.js[https://alpinejs.dev], and [Tailwind](https://tailwindcss.com) for the web part.

However, for the active timer, we better use [ReactPHP](https://reactphp.org).  

So we create one-time timers for Event Time, 
 
 	$timer = $loop->addTimer($time, function() {
		 broadcast(new EventTime(...)); 
	});

and periodic timers for Clock Time,

	$timer = $loop->addPeriodicTimer($time, function() {
	   broadcast(new ClockTime(...));
	});

Communicating with Laravel through the broadcasting of events, `EventTime`, and `ClockTime`.