teleren/devto huggingface dataset:
YDKJS — Objects and Prototypes — Part1
Tags: javascript, webdev, tutorial, beginners
Published: 2019-08-13 16:31:51

Welcome to the second series of You don’t know JS. Part one of the series was regarding Scopes and Closures.

This series is all from the learnings of **Kyle Simpson** and also from the amazing youtube Javascript series by **Kaushik Kothagul** from [Javabrains](https://www.youtube.com/user/koushks/playlists?view=50&shelf_id=1&sort=dd), which is also influenced by **You don’t know JS**.

Let’s start with creating a simple function using object to create employee objects.
```
    function createEmpObj(fName, lName, gender, desig) {
      var newObj = {};
      newObj.firstName = fName;
      newObj.lastName = lName;
      newObj.gender = gender;
      newObj.designation = desig;
      return newObj;  
    }

    var emp1 = createEmpObj("Parag", "Khandar", "M", "Project Manager");
```
> Now consider the line **var newObj = {};** and **return newObj;** They will be same in every function which we create. So, JS gave us a special type of function known as **Constructor function** to create them.

We will refactor the above to use **Constructor function**. Look at the below code.
```
    function createEmpObj(fName, lName, gender, desig) {
      //var this;
      this.firstName = fName;
      this.lastName = lName;
      this.gender = gender;
      this.designation = desig;
      //return this;  
    }

    var emp2 = new createEmpObj("Shikha", "Biswas", "F", "Developer");
```
We are adding the keyword **new** to create the object. It basically takes care of the creation and returning of the newObj. But gives this a new name **this**.
Note, that we don’t need to put those two line in our code and automatically put by JS engine.

Let’s go through the four different ways to execute functions in Javascript.
```
    function foo() {
      console.log("Hello");
    }

    foo();  //Method #1

    var obj = {};

    obj.foo = function() {
      console.log("Hello");
    }

    obj.foo() //Method #2

    new foo() //Method #3
```
The Method#1 is the obvious way to execute a function. 
In Method#2 , we have an object and that object have a property of foo. The property foo have a value as anonymous function. So, obj.foo() can be used to call the function.
The Method #3, we have just seen and is called Construction function and adds the this, when call with new keyword.

We will go through the Method#4 in the next part.
The Pratfall Effect
Tags: pratfalleffect, life, boxpiper
Published: 2020-09-20 10:30:46



Is spilling coffee on yourself or Falling down in public ever beneficial ???

According to social psychology, clumsy mistakes like these can give individuals an advantage more often than you might think. It’s called the Pratfall Effect and remains a highly intriguing theory in the field of social science.

> In social psychology, the pratfall effect is the tendency for an interpersonal appeal to increase or decrease after an individual makes a mistake, depending on the individual's perceived ability to perform well in a general sense. An individual perceived to be highly competent would be considered more likeable after committing a blunder, while a perceived average individual would be considered less likeable.
> 
> <footer>
> <cite>— Wikipedia</cite>
> </footer>

To continue reading, head over to [Box Piper](https://www.boxpiper.com/posts/the-pratfall-effect/) source.

To read more such interesting topics, follow and read <a href="https://boxpiper.com/">BoxPiper blog</a>.

Support my work and [buy me a Coffee](https://ko-fi.com/E1E72C2MM). It'll mean the world to me. 😇

<a href="https://ko-fi.com/E1E72C2MM"><img src="https://cdn.ko-fi.com/cdn/kofi1.png?v=2"/></a>
Compassion
Tags: 100daystooffload
Published: 2020-09-20 09:34:09

Recently I watched a programme called *Ambulance*. Following the daily life of the London Ambulance Service, it's not something I'd ever choose to watch myself. But watching it proved to be such a tonic for these fractured times.

The supply of universal healthcare is taken for granted here and is underappreciated. But there was one case in *Ambulance* that exemplified the compassionate ideal of such a system. In this example, the emergency services were called to a building site where a man has stopped breathing. To make the situation more difficult he was on a higher floor that was difficult to access, and getting him to hospital was not straightforward. Because there are various specialised roles in the service, as many as eight different teams of people attended the scene. At the same time new calls were coming in and each of those were having to be prioritised according to the patients' needs. Unfortunately, despite the efforts of all involved, the man at the building site died.

The story being told was just one of many that took place that day, and in many ways the formula of *Ambulance* was the same as so many others like it. But what struck me was this idea: eight teams of people were sent to the aid of one man who wasn't breathing. Nobody knew who he was, or his background or his prospects. The single aim of those people who went to his aid was to save the life of a stranger. They were unsuccessful in that case, but went on with the rest of their shift and repeated their efforts. They treated the injured ankle of a footballer, the drug-addled man in the street, the kind old lady at home. No questions were asked about whether they could pay, or decisions made about whether they deserved treatment.

In this world where the inequalities between the privileged and the exploited are growing larger, and the corruption used by the privileged is exposed, every example I see of common decency reminds me that there is still some hope out there. It should be nourished and treasured, whilst the poison of hatred and division should be starved of light and oxygen until it finally withers away into an unpleasant memory.

*I'm publishing this as part of 100 Days To Offload. You can join in yourself by visiting [https://100daystooffload.com.](https://100daystooffload.com)*
Save the Prisoner Explain Solution | Javascript
Tags: hackerrank
Published: 2020-09-20 10:22:26

```javascript
function saveThePrisoner(n, m, s) {
  console.log((m-1 + s) % n)
  return (m-1 + s)%n || n;
}

saveThePrisoner(3, 1, 2);
```

[Problem](https://www.hackerrank.com/challenges/save-the-prisoner/problem)
How wakatime motivates me to stay productive
Published: 2020-09-20 10:14:37

For those of you who don't know, [wakatime](https://wakatime.com/) is a plugin that can be integrated into an IDE (or browser) to keep track of how much time you spend coding, as well as showing time spent for different languages and projects. I use it on all my IDEs such as Visual Studio, Visual Studio Code and others which I use on a daily basis.

Wakatime gives me the satisfaction of getting to see and measure how productive I was during the day or the whole week (could be even the month or longer). It truly feels great and fulfilling to see how focused and "in the flow" I really was throughout the work week.

For anyone interested I really recommend using Wakatime, it is free and very simple and it supports [many IDEs, editors](https://wakatime.com/plugins) and [integrations](https://wakatime.com/integrations). 

I also have set up a very cool github profile readme using a GitHub action provided by [avinal](https://github.com/avinal/Profile-Readme-WakaTime), you can check mine out on my github profile [dimitrov-d](https://github.com/dimitrov-d)
Redux A short intro.
Tags: react, redux, reactnative, javascript
Published: 2020-09-20 10:14:01

###**Redux - A short introduction**

>From the documentation , Redux is a predictable state container for JavaScript apps.To put simply its a JS App Data Flow Architecture.

Modern UI Libraries in order to entertain cool UI Features make   use of states(States are just like variables, but variables on   which a ui component depends). Redux is a data flow architecture  which allows us to handle app state in rather easy and well to maintain way.

>**NOTE : Redux is used for larger apps i.e where there is a lot of UI Components involved and their change depends on data.**

####Redux Building Blocks
 * **Store**

   >Store is the object that holds the application state.

Yup ! The entire state of an app is represented by store.        The store provides some methods to interact, Dispatch actions,        Register any listeners e.t.c.

 * **Actions**

   >Simply, Actions are events.

Store is only changed by actions, actions are basically requests   which sends data to store and then from store app access the    states.

 * **Reducers**

>Reducers are pure functions which based on actions returns the   next state.


![ReduxDataFlow](https://dev-to-uploads.s3.amazonaws.com/i/ewzeke9hfo4ks27e8qeh.png)

_*This is the most basics of redux. To know more hop over to the links below._


####_Useful Links_
 * [Redux Introduction.](https://www.smashingmagazine.com/2016/06/an-introduction-to-redux/)
 * [A short Intro to Redux explained very nicely.](https://www.youtube.com/watch?v=nFryvdyMI8s)
 * [Redux Docs](https://redux.js.org/)
A simple problem and the solution in many programming languages
Tags: programming, beginners
Published: 2020-09-20 10:00:24

---
title: A simple problem and the solution in many programming languages
published: true
description: I want to recopile the solution to simple programming problems such as defining a string variable, concatenating two strings or replacing a text in many languages as posible.
tags: programming, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/64zat14mosvuy4q889lk.png
---

Usually to find the code equivalent from one language to another one I use google and stackoverflow, I want to make something easier to use.

I want to recopile the solution to simple programming problems such as defining a string variable, concatenating two strings or replacing a text in many languages as posible.

![Debug](https://dev-to-uploads.s3.amazonaws.com/i/x17xbgjfjdt2vaanv4v6.png)

I think this can be very useful when you want to learn a new language or you need to switch between them, you know the theory but maybe you don't know the syntax.

If you know a better solution for a problem or you are missing a programming language solution all the pull request are welcome.

[Link to the GIT repo](https://github.com/vivirenremoto/full_code_alchemist)
How to create 6 hover effects to buttons
Tags: html, css, javascript, frontend
Published: 2020-09-20 09:43:51

---
title: How to create 6 hover effects to buttons
published: true
description: How to create 6 hover effects to buttons only with html and CSS
tags: html,css,javascript,frontend
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/usyhs9egwq0jwlar301p.png
---
Post > https://www.instagram.com/p/CFVJcvtCDiu/
Codepen: https://codepen.io/luisdanielroviracontreras/pen/NWNOOwz
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/usyhs9egwq0jwlar301p.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/l4sdekirxh5hjfjv3nbj.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6qtl863fcjz3gj1fpl8p.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mv96592tk39inrv0xekm.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ynt7tb7abjw6di2seznu.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2nyjrd5g6e043cqfivuy.png)

More Post > https://www.instagram.com/luisdanielroviracontreras/
A neat way to add Redux computed value by custom hook
Tags: react, redux, hook, javascript
Published: 2020-09-20 09:41:40

Someone who starts `react` project usually have to decide a global state library `redux` or `mobx`.
`redux` has a more stars in github than `mobx` but `mobx` has a unique point with `@computed`. It is an easy way to get computed value with javascript decorator pattern. Of course, `redux` can do the same thing by using `reselect` library. 

As `react` implement 'hook', developers can make easily the computed value.

Assume you have `fruitStore` keeping price and discount data fetched by your server. 

```typescript
const initialState: FruitStore = {
  apple: { discount: 0.03, price: 1000 },
  orange: { discount: 0.12, price: 3000 },
  grape: { discount: 0.2, price: 8000 },
  ...
};
```

This data will be displayed in 3 ways at `Tag` Component.
1. discounted price
2. final billing price to the payment
3. readable discount value with '%'

for this, you have to calculate as below

```typescript
const discountedPrice: number = price * discount;
const billingPrice: number = price * (1 - discount);
const discountPercent: string = `${discount * 100} %`;
```

If have multiple components using these values, you have `ctrl + c`, `ctrl + v`. It makes it harder to read and re-write code.
You may think the store keeps these all data in redux. But it may force the nested object structure and become more complex as view component incremented.

Then let's write simple and efficient code with `useMemo` and custom hook.

```typescript
// custom hook
function useFruitTag(fruit: string) {
  const { discount, price } = useSelect(({ fruitStore }) => fruitStore[fruit]);

  const discountedPrice = useMemo(() => price * discount, [discount, price]);
  const billingPrice = useMemo(() => price * (1 - discount), [discount, price]);
  const discountPercent = useMemo(() => `${discount * 100} %`, [discount]);

  return {
    discountedPrice,
    billingPrice,
    discountPercent,
  };
}

// component
function AppleTag() {
  const { discountedPrice, billingPrice, discountPercent } = useFruitTag('apple');

  return (
    <div>
      <h1>Apple</h1>
      <p>{discountedPrice}</p>
      <p>{billingPrice}</p>
      <p>{discountPercent}</p>
    </div>
  );
}
```

This way makes computed value without another library `reselect` or `mobx`. By using `useMemo`, you can use cached value and maintain easily code even if view and fruits incremented. And also, the most important thing I think is that you can distinguish various logic as you want.


p.s
This article means not that `useMemo` can replace `reselect` or what. You can read more details from [here](https://github.com/reduxjs/reselect/issues/386)
The perfect way to check for a palindrome, in JavaScript
Tags: javascript, palindrome
Published: 2020-09-20 09:34:44

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fvh1zsp7uaj2z0m04e6y.jpg)

First, let's clarify what a palindrome is.

According to Wikipedia "a palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward".

In the above definition, the word "reads" is key: a phrase like "Red rum, sir, is murder" is *read*, not written the same backward as forward. That is because of the *punctuation* and *case*. 

The above is a clue for what the first two steps we need to take are: *eliminate punctuation and spaces* and *force lower case*. 

After that, we can proceed with getting *comparing the string to check with its reverse*.

The function looks like this:

     const isPalindrome = (str) => {
      // Force to string
      // Eliminate punctuation and spaces
      // Force lower case
      // Split
      let arr = str.toString().replace(/[^A-Za-z0-9_]/g, "").toLowerCase().split('');

      // Join into one word
      let joined = arr.join('');

      // Reverse and join into one word
      let reverseJoined = arr.reverse().join('');

      //compare
      return joined == reverseJoined;
    }

After making sure our expression-to-check is a string, we use `str.replace(/[^A-Za-z0-9_]/g, "")` to eliminate punctuation and spaces and force lowercase with `toLowerCase()`. 

We need to make an array from the resulted string, so that we get the reverse of the string by reversing the array and then joining it into a string. This is the "original" array:

    let arr = str.toString().replace(/[^A-Za-z0-9_]/g, "").toLowerCase().split('');

The "original", lower case, no spaces, no punctuation string:

    let joined = arr.join('');

The *reversed* string:

    let reverseJoined = arr.reverse().join('');

Finally, the comparaison, that returns a Boolean:

    return joined == reverseJoined;

And with that we are done making a palindrome checker that works for words and phrases too. You can see it in action **[here](hhttps://jsfiddle.net/Lebwsj8v/)**.
Optimizing moment-timezone using webpack
Tags: javascript, webdev, webpack
Published: 2020-09-20 09:21:36

[moment-timezone](https://momentjs.com/timezone/) is an awesome tool to have when working with different time-zones.

While the tool is great it also has lots of data that we might never use, bloating the size of our applications.

We can do better!

## But first, some facts

To optimize an application we need to know some things about it.

Imagine that we have an application that is providing a search functionality for scientific articles.

- Each article has information about it's creation and last modification dates.

- The oldest article is from 1990.

- Our application is being used by universities in Europe and Australia only.

### So we need the following timezone data
- time-zones from Europe and Australia only
- year range from 1990 - 2020 (present year)


## Optimizing based on our needs
Now that we know what we need, we can start the optimization.

We will use a webpack plugin called [moment-timezone-data-webpack-plugin](https://github.com/gilmoreorless/moment-timezone-data-webpack-plugin) to keep only the data we need from our application.

#### Install the plugin
`npm i -D moment-timezone-data-webpack-plugin`

#### Adding the plugin to webpack

For simplicity I will only show the plugin related configuration in the webpack file.

```javascript
const MomentTimezoneDataPlugin = require('moment-timezone-data-webpack-plugin');

module.exports = {
  plugins: [
    new MomentTimezoneDataPlugin({
        matchZones: [/^Europe/, '/^Australia/'],
        startYear: 1990,
        endYear: 2020,
    }),
  ]
};
```
And that's it :)

Now our application will have only the timezone data that we actually need!

Happy coding! :)
Notes on pre-rendering
Tags: javascript, html, nextjs, gatsby
Published: 2020-09-20 09:01:26

Typical single page applications needs to load all JavaScript before rendering the application. This increases the time for FP (First Paint) and FCP (First Contentful Paint). However this can be mitigated using pre-rendering. Pre-rendering is generating the HTML from server and sending to the browser.

There are two types of pre-rendering techniques. SSR (Server Side Generation) and SSG (Static Site Generation). Both of these techniques create the HTML in the server and send back to the client, thus improving FP and FCP. However the difference is that,
1. SSR, HTML is generated for each request.
2. In SSG, HTML generation is done at the build step of the application.

With SSR dynamic content as such data from APIs are fetched at each time. But with SSG if such dynamic content is present they can become stale. In different frameworks there are techniques to overcome this issue to a certain extent. In Next.js, it is possible to SSG an application without the dynamic content or add incremental static site generation. SSG can provide better performance with CDN cache.
SEO Meta Tags
Tags: seo, boxpiper
Published: 2020-09-20 08:56:27


Search engines such as Google use metadata from meta tags to understand additional information about the webpage. They can use this information for ranking purposes, to display snippets in search results, and sometimes they can ignore meta tags.

Meta tags are snippets of code that tell search engines important information about your web page, such as how they should display it in search results. They also tell web browsers how to display it to visitors.

Often meta-tag data shows up whenever someone shares a link on social media, in messaging, or in your business chat software

Search engines scan your site to figure out what it’s all about and it’s authenticity.

## Best practices

- **Title - Very Important**. The most important meta tag for ranking is your title tag. Write a unique title tag for each page. Keep it under 60 characters. Be brief, but descriptive. Use sentence case or title case. Match search intent;

```
<meta name="title" content="Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.">
<meta property="og:title" content="Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.">
<meta property="twitter:title" content="Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.">
```

Google only gives us 60 characters for your title and about 105 characters for our description—the perfect opportunity to tightly refine our value proposition.

- **Image - Moderately Important**. It is the most valuable graphic content you can create to encourage users to click and visit your website. On sites like Facebook, Twitter, and Linkedin, your meta image is 3x larger than your text content!

```
<meta property="og:image" content="https://www.notion.so/images/meta/default.png">
<meta property="twitter:image" content="https://www.notion.so/images/meta/default.png">
```

To continue reading, head over to [Box Piper](https://www.boxpiper.com/posts/seo-meta-tags/) source.


{% youtube LEUb_wTHv4I %}

To read more such interesting topics, follow and read <a href="https://boxpiper.com/">BoxPiper blog</a>.

Support my work and [buy me a Coffee](https://ko-fi.com/E1E72C2MM). It'll mean the world to me. 😇

<a href="https://ko-fi.com/E1E72C2MM"><img src="https://cdn.ko-fi.com/cdn/kofi1.png?v=2"/></a>
Learning Management System - BIS (Backend)
Tags: devops, node, mongodb, javascript
Published: 2020-09-20 08:41:40

This is a School Management System for Bright International School. This is the backend end project. We have used NodeJS to develop this and we used MongoDB as our database. It manages all the student, teacher, and class details and it also generates custom student reports such as Student details. Also, it shows all the statistics related to students, teachers, classes, and subjects. 
#angular #javascript #nodejs #mongodb 
{% github suharaaa/bis-backend %}
Multiple Events to a Listener with JavaScript
Tags: javascript, productivity, beginners
Published: 2020-09-20 08:36:00

When we code we usually have one event for one listener but there are cases where we need to add more that one event for the same listener.
## Wrong way
The first thing that can come to our mind can be the next code:

![Fail](https://dev-to-uploads.s3.amazonaws.com/i/6xj6jkgfh8dx4a0cmbgg.png)
 
But It’s not possible to add two different events for one listener like we did above, so we have different ways to achieve our goal and I will show you 3 ways to do it.

## Way 1
>We can create 2 events listeners each one for the button element.

![Code1](https://dev-to-uploads.s3.amazonaws.com/i/g2w1lvhh2qc2j02kp6jq.png)
 
## Way 2
>We can create a variable ***“myEvents”*** to store the event listeners and split them and finally loop with a ***forEach*** and assign each event listener.

![Code2](https://dev-to-uploads.s3.amazonaws.com/i/vq21cmjx3ve6fnj0kn2v.png)

## Way 3
>We can store our event listeners into an array and loop with a **forEach** and assign each event listener.

![Code3](https://dev-to-uploads.s3.amazonaws.com/i/n9dzzph4uqei25pmzxde.png)
 
## Results
You can watch the results of the code we have seen above in the next image. If you want to test it you can download the code which is store in Github in the next link as a little project:

>[Link Github Project](https://github.com/ferdunt/Javascript-tutorials/tree/master/Multiple%20events%20to%20a%20listener)

![Results](https://dev-to-uploads.s3.amazonaws.com/i/q237hxgi87cqrpnon1j2.png)
 
## Conclusion
>The “Way 3” is the best option so far if we want to add multiple events to a listener this way you can avoid rewrite the same code over and over again and remember “Don’t Repeat Yourself”.