teleren/devto huggingface dataset:
Arrow Function and The new, arguments & super Keyword!
Tags: javascript, codenewbie, 100daysofcode, beginners
Published: 2020-08-02 03:17:37


We learned about [arrow functions](https://bhagat.me/blog/2020/06/11/arrow-functions.html) and how it [behaves differently](https://bhagat.me/blog/2020/06/13/arrow-functions-this-keyword.html) with [`this` keyword](https://bhagat.me/blog/2020/06/12/this-keyword.html).

Arrow functions behave differently when it comes to `this` keyword. It also has no bindings to `arguments`, `new`, and `super` keyword!

### Arguments

The `arguments` object is an Array-like object that allows us to access all the arguments passed to a function.

```javascript
function addThreeNumbers(a, b, c) {
    console.log(arguments.length); // 3
    console.log(arguments[0]); // 4
    console.log(arguments[1]); // 17
    console.log(arguments[2]); // 22
    return a + b + c;
}

console.log(addThreeNumbers(4, 17, 22)); // 43
```

`arguments` for arrow functions is a reference to the arguments of the enclosing scope instead.

```javascript
const bar = x => console.log(arguments);

console.log(bar()); // Uncaught ReferenceError: arguments is not defined
```

We can solve this "problem" with a workaround. Use the `rest` operator when you need access to arguments.

```javascript
const addThreeNumbers = (...args) => {
    console.log(args.length); // 3
    console.log(args[0]); // 4
    console.log(args[1]); // 17
    console.log(args[2]); // 22
    return args[0] + args[1] + args[2];
}

console.log(addThreeNumbers(4, 17, 22)); // 43
```

You can make the above example a bit cleaner using destructuring.

```javascript
const addThreeNumbers = (...args) => {

    const [a, b, c] = args;

    console.log(args.length); // 3
    console.log(a); // 4
    console.log(b); // 17
    console.log(c); // 22

    return a + b + c;
}

console.log(addThreeNumbers(4, 17, 22)); // 43
```


### New

Arrow functions cannot be used as constructors. `new` will throw an error when used with arrow functions.

```javascript
const foo = () => { };
const bar = new foo(); // foo is not a constructor
```

Arrow functions are missing a [Construct](http://www.ecma-international.org/ecma-262/6.0/#table-6) internal method.

### Super

We cannot use the `super` keyword with arrows either per ES spec.

```javascript
class Base {
    public foo = () => {
        console.log("Hello");
    }
}

class Child extends Base {
    public bar() {
        super.foo(); // Only public and protected methods of the base class are accessible via the 'super' keyword.
    };
}
```

Instead, use regular functions in such a case.

```javascript
class Base {
    public foo() {
        console.log("Hello");
    }
}

class Child extends Base {
    public bar() {
        super.foo();
    };
}
```

### Bonus 🤑

* Arrow functions do not have a `prototype` property.
   ```javascript
   var Foo = () => { };
   console.log(Foo.prototype); // undefined
   ```
* Arrow functions cannot be used as generators. They do not have a `yield` keyword.
My Fake Bank
Tags: reactnative, react, project, android
Published: 2020-08-02 02:12:07

---
title: My Fake Bank
published: true
description: 
tags: reactnative,react,project,android
//cover_image: https://direct_url_to_image.jpg
---

# Oppongs Fake Bank - React

I made this app because I am still in the process of learning how to use react native, I chose this because I wanted to learn how to use Redux as well.

## Getting Started

- Download files and unzip them
- run yarn install, and npm install

## Running program

- After the previous step, run the command below in the main project folder

```
expo start
```
<p float="left">
<img style="-webkit-user-select: none;margin: auto;" width="150" src="https://lh3.googleusercontent.com/YER-I7F_Z-y_DSAPJelB0A09aZbX-WsnpKpuP76PGvDSMmHGGy-lvm4IEC5zN7hVLdg=w2628-h1766-rw">

<img style="-webkit-user-select: none;margin: auto;" width="150" src="https://lh3.googleusercontent.com/Tx4nA2PmJD0O1CVdoJ-0xS79mE6RfDD9v7GxUAG1Yq0DHeVXPQsmce0CnbdmS18Oq2Q=w2628-h1766-rw">


</p>

## Future Work

- In the future, I hope to be able to add an online feature where you can authenticate and connect to an online database.
  
## Acknowledgments

- mosh
- react-native, 
- expo
- redux

## Author

- Michael Oppong


## Link to GooglePlay Store

 [Here](https://play.google.com/store/apps/details?id=com.its_oppong_studios.OppongsBank)

 there isn't a link to the ios store because I am broke :(
Node.js membuat Javascript luar biasa
Tags: javascript, node, v8
Published: 2020-08-02 02:07:23

Komputer tidak memahami bahasa selain 0 dan 1 (*binary digit*), lalu bagaimana bisa komputer memahami bahasa pemrograman seperti *Javascript*?

Bahasa pemrograman mempunyai *engine* agar komputer dapat mengerti kodenya, setiap barisan kode tersebut akan diterjemahkan oleh *engine* itu sebelum diterima oleh komputer, misalnya *Java* yang mempunyai JVM (*Java Virtual Machine*), *Javascript* juga mempunyai *engine* untuk menerjemahkan kodenya agar dapat dibaca oleh komputer. *Engine Javascript* tertanam pada *browser* sehingga dibutuhkan *browser* agar komputer dapat menjalankan kode *Javascript*.

Ada banyak *browser* saat ini seperti *Firefox, Opera, Safari, Chrome*, dll. Dan masing-masing dari mereka mempunyai *engine* tersendiri untuk menerjemahkan kode *Javascript*. Saat ini ada 8 *engine Javascript*, misalnya *Firefox* dengan *SpiderMonkey*, *Safari* dengan *JavaScriptCore*, dan *Chrome* dengan *V8*.

Perkembangan *Javascript* dimulai saat adanya *engine* dari *Google* yang bernama *V8*, tujuan *Google* menciptakan *engine* ini yaitu untuk memaksimalkan layanan *Google Map* yang membutuhkan kecepatan tinggi saat me-*load* semua *resource*-nya karena *engine* yang ada tidak dapat memaksimalkan semua fitur layanan ini.

Saat ini, *engine V8* adalah *engine* yang tercepat yang mempunyai performansi yang bagus. Karena alasan itu, Ryan Dahl yang sedang mencari teknologi untuk meningkatkan performa website memutuskan untuk menggunakan *engine Javascript V8* yang akan dipakai pada Node.js.

Karena itu, Node.js membuat *Javascript* yang tadinya hanya untuk interaksi web dan hanya berjalan di sisi *client* sekarang berubah dan berevolusi menjadi bahasa *universal* yang hampir dapat berjalan di *client* maupun *server*, dan hampir di semua *platform*.

Node.js membuat *engine Javascript* ada diluar *browser* sehingga dapat mengeksekusi *Javascript* diluar *browser*. Karena itulah mengapa *Javascript* dapat berjalan di sisi *server* dan membuat program *Javascript* dapat dieksekusi dimanapun.
LeetCode: Longest Consecutive Sequence
Tags: leetcode, algorithms
Published: 2020-08-21 07:13:37

---
title: LeetCode: Longest Consecutive Sequence
published: true
date: 2020-08-02 01:32:00 UTC
tags: LeetCode,Algorithms
canonical_url: https://coderscat.com/leetcode-longest-consecutive-sequence
---

## Challenge description

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

```
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
```

## Naive Solution: Use set to check consecutive elements

We use a `set` to check whether one element exists in array. Iterate all the elements and try to find the longest sub-array in the loop.

But the overall time complexity is O(N^2), which will time-limited.

```cpp
class Solution {
public:

  set<int> S;

  int longestConsecutive(vector<int>& nums) {
    for(auto i: nums)
      S.insert(i);

    int ans = 0;
    for(auto i: S){
      int n = i + 1;
      int cnt = 1;
      while(S.count(n)) {
        cnt++;
        n++;
      }
      ans = max(ans, cnt);
    }

    return ans;
  }
};

```

## An Optimization on the previous solution: reduce duplicated checking

The duplicated checking happened at a long consecutive array, suppose we have `3, 4, 5, 6, 7`.

First, we checked with 3, and then checked at 4, and 5 …

This could be avoided if we test whether i-1 has been checked.

```cpp
class Solution {
public:
  set<int> S;

  int longestConsecutive(vector<int>& nums) {
    for(auto i: nums)
      S.insert(i);

    int ans = 0;
    for(auto i: S){
      if(!S.count(i-1)) {
        int n = i;
        int cnt = 1;
        while(S.count(n+1)) {
          cnt++;
          n++;
        }
        ans = max(ans, cnt);
      }
    }
    return ans;
  }
};

```

## Use union-find to store relationships of elements

`union-find` is an elegant data structure to store and query consecutive relationships. `U` will store the next larger elements of one element.

Iterate with all the elements, try to find the largest element from one starting point, and the distance of two elements will be the number of consecutive elements.

```cpp
class Solution {
public:
  map<int,int> U;

  int find(int x){
    return U.count(x) ? U[x] = find(U[x]) : x;
  }

  int longestConsecutive(vector<int>& nums) {
    for(auto i: nums)
      U[i] = i+1;

    int ans = 0;
    for(auto i: nums){
      int y = find(i+1);
      ans = max(ans, y-i);
    }
    return ans;
  }
};

```

The post [LeetCode: Longest Consecutive Sequence](https://coderscat.com/leetcode-longest-consecutive-sequence) appeared first on [Coder's Cat](https://coderscat.com).
Lets do some magic tricks with Go Slices
Tags: go, tutorial, video
Published: 2020-08-02 01:30:32

{% youtube 5o97pT9A1d4 %}

I have began offering 1-on-1 mentoring, if you want to learn more, please visit and fill out this [form](https://bit.ly/2OQLkmH) if interested

Slices in go are very powerful and you can accomplish quite a lot with them. In this video I demonstrate some common tricks you can do with them, such as inserting values at a specific index in the slice or inserting a slice into another slice!

If you liked it and want to know when I post more tutorials, be sure to [subscribe] (https://www.youtube.com/DonaldFeury?sub_confirmation=1) and thank ya'll again for your time!
Generating a gitignore file
Tags: git, github, gitignore
Published: 2020-08-02 01:26:58

Here is a simple but usable .gitignore file:

```gitignore
# Python
*.py[cod]
__pycache__
venv/
htmlcov/
.tox/
.coverage
.coverage.*
.mypy_cache/

# Node/npm
node_modules

# Editors
*.sublime-workspace
*.sublime-project # unless most use Sublime
.vscode
*.code-workspace
.idea
*.swp
*~

# Misc
.DS_Store
```

This is simply a list of files, or rather a list of file _patterns_ that should be excluded from version control. The file is named `.gitignore` and I usually place just one in the root of my project directory.

The patterns themselves can get rather complex. One can [learn from the docs][gitignore], of course. It is worth a look, at the least.

Thankfully, however, a few resources exist to more easily guide the generation of `.gitignore` files.

## [GitHub starter examples][github/gitignore]

GitHub provides numerous examples to get you started, available in the [github/gitignore] repo. You may select your language and build from there.

## [gitignore.io]

The online generator [gitignore.io] provides a place to select the desired languages and editors, and have a custom `.gitignore` built for you.

If you know your team well, you can select the editors you know they use, along with the language/platform the project uses. This offers peace of mind, knowing you are not hindering your fellow devs, or spawning needless Emacs vs Vim wars.

## [gig], a cli for gitignore.io

To install [gig], first [install go](https://golang.org/doc/install) (your package manager may call it golang), then install [gig]:

```bash
go get github.com/shihanng/gig
```

Once installed, `gig list` will show you all templates available. `gig search` allows you to search if [`fzf`](https://github.com/junegunn/fzf) is installed.

Then, pass in a series of templates to use, and your `.gitignore` will be printed:

```bash
gig gen python vim
```

## Customize and trim the `.gitignore`

Once you have a `.gitignore`, take a look if there are lines that are irrelevant, given the tools you use. For instance, if you are using Python but not Mypy, you can eliminate the `.mypy_cache/` line. If you are using Node but not Grunt, you can eliminate the `.grunt` line.

While removing extraneous lines is not truly necessary, a simpler file is usually an easier file to maintain.

Once you have a `.gitignore` you like, you will very likely simply copy it into new projects. But it is nice to know there are tools available when you need them.

[gitignore]: https://git-scm.com/docs/gitignore
[gitignore.io]: https://www.toptal.com/developers/gitignore
[github/gitignore]: https://github.com/github/gitignore
[gig]: https://github.com/shihanng/gig
eSlayers part 7 - fetching more data for math history
Tags: javascript, react, nextjs, typescript
Published: 2020-08-02 01:09:42

Last post I was working on fetching data and trying to get some information to display for player match history. Now that I can fetch data from the match API I am going through and pulling all relevant data for match history

So far I have
* Player name
* Placement
* Gold left
* In-game level
* Players eliminated
* Trait of units used
  * Trait name
  * Number of units
  * Tier style
  * Tier of trait
* Units
  * Unit name
  * Tier
  * Items

This is what my `Match.tsx` component looks like now
![Match Component](https://dev-to-uploads.s3.amazonaws.com/i/dmzrvr05jyxca20fs5od.png)

And how it looks in localhost
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dd1jdkqom4lvgws9ty9n.png)

So now that I have match history I want to pull more information related to the summoner. So in my case, I would like to pull some stats for Rjeezy. 

Here are the data points I am looking to get for the summoner:
* Average placement
* Trait stats for the last 20 games
* Most used units

So next up I will create some logic that will filter out all players besides the summoner so I can get access to summoner specific data for the data points I am trying to show.
My typeof Radio: Un podcast de Desarrollo Web en Español
Tags: webdev, podcast
Published: 2020-08-02 01:08:22

¡Hola!

{% spotify spotify:episode:2KjP3WKOcyg4FRilStCDU5 %}

Mi amigo Arturo Mosqueda y yo estamos empezando a aventurarnos en esto del podcasting con uno propio, que nombramos ["My `typeof` Radio: Un podcast de Desarrollo Web en Español"](https://mytypeofradio.buzzsprout.com/).

Somos devs de México y nos gusta mucho platicar de varios temas relacionados con desarrollo web y queremos compartirlo con otras personas.

Tenemos planeados varios temas y _tipos_ de episodios (😉😉).

Puedes encontrarnos en [Spotify](https://open.spotify.com/show/6oPZBuoJxLWsj6X5SRJ8e9), [Apple Podcasts](https://podcasts.apple.com/us/podcast/my-typeof-radio/id1525642310), [Stitcher](https://www.stitcher.com/podcast/my-typeof-radio),[Overcast](https://overcast.fm/itunes1525642310/my-typeof-radio), [Castro](https://castro.fm/podcast/a10a3f41-2e32-4168-8523-da88104cf8af), [Castbox](https://castbox.fm/channel/id3161644) o [Deezer](https://www.deezer.com/us/show/1572012).

Si ninguno te sirve, también tenemos un RSS feed: https://feeds.buzzsprout.com/1190693.rss

Estamos echándole muchas ganas para preparar los temas y producir el contenido. ¡Ojalá que nos puedas acompañar!😁
Code Snippet Series: Remove Junk from Array
Tags: javascript, algorithms, performance, beginners
Published: 2020-08-02 00:27:48

# Quiz
There are two key areas to increase the performance of this code without losing robustness; can you spot them?


```JS
/**
@func 
remove junk (non-value-based data) from an arr

@param {*[]} a
@return {*[]}
*/
export const removeNonVals = a => a.filter(v => {
  return v !== null && v !== undefined
    && !(v.constructor === String && v.trim() === "")
    && !(v.constructor === Object && Object.keys(v).length === 0)
    && !(Array.isArray(v) && v.length === 0)
});

//@tests

//@fixtureData
const aDirty = [
  "Casbah", "abcd",
  "", "p",
  "", "255",
  undefined, null,
  "", "     ",
  [], {}, "[]", "{}"
  [[]],
  [["nested"]],
  NaN, Infinity, 0, -0,
  5, -1, 1e30, BigInt(3145),
  n => n
  , , , , ,
];

const aClean = removeNonVals(aDirty);
console.log(aClean);
/*
@output
[
  'Casbah',               'abcd',
  'p',                    '255',
  'Warsaw',               '1855',
  '[]',                   [ [ 'nested' ] ],
  NaN,                    Infinity,
  0,                      -0,
  5,                      -1,
  1e+30,                  3145n,
  [Function (anonymous)]
]
*/

//@perftest
timeInLoop("removeNonVals", 1e6, () => removeNonVals(aDirty))
/*
removeNonVals: 1e+6: 2.601s
*/
```


# TimeInLoop Source Code
https://gist.github.com/funfunction/91b5876a5f562e1e352aed0fcabc3858
Deploy ReactJS em Servidor Apache
Tags: react, deploy, apache, dev
Published: 2020-08-02 00:01:08

Salve clã! 😁 

Este post é como resolvi um problema que tive essa semanal quando tive que fazer o deploy de um projeto ReactJS em um servidor Apache. Acho interessante compartilhar com vocês.

Sem mais enrolação! 🚀

Todo o processo de criação e produção de seu projeto continua o mesmo. Entretanto temos alguns pontos pra ressaltar.

Devemos adicionar no arquivo .htaccess, que deve ficar no diretório que contem o arquivo index.html, o seguinte:

```
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
```

Outro ponto importante, e foi onde eu empaquei é 🤔, caso seu projeto fique como um subdominio do site como: https://myapp.com/the-app, você deve especificar isso no seu Router dentro do seu projeto. 
Esta informação deverá estar presente no BrowserRouter na opção basename="/the-app", caso contrario o React interpretará que seu projeto estará na raiz do domínio.

Abaixo temos um exemplo:

```
import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import Home from "./pages/home";
import Support from "./pages/support";

export default function Routes(){
    return(
        <BrowserRouter basename="/the-app">
            <Switch>
                <Route path="/" exact component={Home} />               
                <Route path="/support" component={Support} />
            </Switch>
        </BrowserRouter>
    );
}
```

Além disso devemos também adicionar no arquivo package.json a tag homepage com a url completa que seu projeto estará hospedado. Ex: https://myapp.com/the-app 

Não mencionei porém todos já devem estar cientes que depois de todas as alterações feitas, devemos executar o script **build** para a criação de uma versão otimizada pronta para ser posta em produção. Devemos mover apenas os arquivos que estarão dentro da pasta build para o servidor Apache, não se esqueça disso! 😅

Este pequeno detalhe de adicionar o basename no BrowserRouter me custou algumas horas de pesquisa, espero que eu tenha te ajudado. 🥰

Para mais veja meu [Github](https://github.com/GuiSelair). 😎
You don't know the first thing about functions in JavaScript
Tags: javascript, webdev, tutorial, beginners
Published: 2020-08-01 23:39:05

#The point of this article is to give you an 'A-ha!' moment about functions in JavaScript.

##This function returns the sum of two numbers
```
function sum(a, b) {
  return a + b;
}
```

###To call - or invoke - this function, you'd write this:
```
sum(2, 3) // returns 5
```

###How you might imagine this function works is:
```
function sum(2, 3) {
  return 2 + 3;
}
```

###However, two additional steps happen:
```
function sum(a, b) {
  let a = 2;
  let b = 3;
  return a + b;
}
```

###What I hope this walkthrough showed you:
- When you define a function, you declare the expected parameters and their respective unique labels (e.g. a and b)
- When called, you explicitly specify the arguments you want the function to use as its parameters
- When evaluated, the function assigns each value passed as argument (or a copy of that value) to its parameters
- The function then proceeds to evaluate its body using the values passed when called, aliased as the labels you defined when the program compiled

#This tutorial was short, clear, and fun. I made a game just like it to help you teach yourself frontend
[Fix a function!](http://freecodegame.com)
Git for Dummies (like me)
Tags: git, github, spanish
Published: 2020-08-01 23:19:15

### Configuración inicial
```git
git config --global user.name "your name"

git config --global user.email "your_mail@mail.com"
```

### Inicializando Git
```git
git init
```
Esto comando crea una carpeta .git en nuestro directorio de trabajo, donde se almacenará información de todos los cambios que realicemos a nuestro proyecto.

### Clonando repositorio remoto
```git
git clone <link>
```
con este comando "copiamos" a nuestra carpeta local todos los archivos y carpetas de un repositorio remoto.

### Agregando los cambios de los archivos
```git
git add <archivo.ext>
or
git add -A
or
git add .
```
Para guardar los cambios realizados primero debemos prepararlos, esto puede ser archivo por archivo, o todo el conjunto total de modificaciones.

### Preparando la subida
```git
git commit -m “<message>”
```
Este comando guarda los cambios realizados al código, le agrega un id o head a dicho "guardado", todo esto dentro de nuestro servidor local. El parametro "message" es un comentario para poder diferenciar diferentes subidas.

### Subiendo cambios a servidor local
```git
git pull origin <branch>
```
Este comando sube una copia de los cambios realizados en el codigo a nuestro servidor local. El parametro "branch" se refiere a la rama de nuestro servidor donde subiremos nuestros archivos, la rama principal es "master".

### Subiendo cambios a servidor remoto
```git
git push origin <branch>
```
Esto sube nuestos cambios al branch (o rama) de nuestro repositorio remoto, la rama principal es "master".


### Otros comandos
```git
git status
```
Muestra el estado actual de los cambios realizados desde el ultimo commit, los archivos nuevos creados, y los cambios en los diferentes archivos.

```git
git branch
```
Nos muestra la rama actual donde nos encontramos

```git
git reset --hard origin/master
```
Regresa el repositorio local al estado del repositorio remoto, se pierden los datos que has realizado desde el ultimo push.

```git
git checkout -b <new branch>
```
Crea una nueva rama, y nos redirige allí.

```git
git checkout <branch>
```
Nos cambia de rama.
A Simple Color Picker using HTML
Tags: html, webdev, newbie, first
Published: 2020-08-01 23:06:51

Hello, World!

As my first post, i would like to introduce myself. I'm Pedro (Peter, if you prefer), i'm 21yo and I'm starting to learn web.

So the other day i checked [this Ananya's post](https://dev.to/ananyaneogi/html-can-do-that-c0n) about simple tools you can do with HTML. I really liked, so i made some of them. The Color Picker caught my attention and i decided to improve it. This is my version of Ananya's Color Picker. I added a white panel to make things visible when selecting colors close to black. In addition, it now also displays RGB and HSL codes:


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



The first step is to create a div box and assign the following CSS:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gv82uk7flznsrbjeah83.png)
_Several successive box-shadows make shading prettier and smoother_


After that, I put a list to standardize the elements that would be added:

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

Finally, it is necessary to create functions in home.js to convert hexadecimal to other formats. For this, I created a function that takes colorCode.innerHTML in string format and returns it in number. That way it facilitates future conversions ;)

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

Conversion functions are easily found on the web. You can also add new conversion functions just by putting a new element to the list (home.html) and its functions in home.js. Just be careful that the functions receive and return an array of numbers. I know there is a better way to do this, but I didn't spend much time on it.

You can find the code in [this repo](https://github.com/GroovyDog/Palette)

This is a very simple tool but great for beginners (like me) to learn HTML.