teleren/devto huggingface dataset:
Acing Your Interview: Traversing a Linked List in JavaScript
Tags: javascript, interview, career, programming
Published: 2020-05-06 11:59:29

---
title: 'Acing Your Interview: Traversing a Linked List in JavaScript'
published: true
description: Traversing a linked list data structure is a common interview question. Today, we'll explore how to do so in JavaScript.
tags: javascript, interview, career, programming
canonical_url: https://typeofnan.dev/interview-practice-traversing-a-linked-list-in-javascript/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/lubpew3ijxwfwxepysas.jpg
---

Traversing a linked list data structure is a common interview question. Today, we'll explore how to do so in JavaScript.

## 🎥 The Video Version

Prefer video tutorials? I made a walkthrough of this interview question solution on YouTube!

{% youtube OG-iaGQwVps %}

---

# The Linked List Data Structure

An example of a linked list is an ordered list of numbers. For example:

```
5 -> 3 -> 10
```

In JavaScript, a linked list tends to be represented as an object with a value and a reference to the next item in the list. Our aforementioned list of numbers could be represented as follows:

```javascript
const linkedList = {
  val: 5,
  next: {
    val: 3,
    next: {
      val: 10,
      next: null,
    },
  },
};
```

# How to Traverse? Let's Take Some Hints from the Structure

So our assignmnet is to traverse this list and put its values into an array: `[5, 3, 10]`.

To do so, we're going to take a hint from the data structure. We can se that, if `next` has a value, there are more elements to traverse. if `next` is `null`, we're done.

We'll start with an empty array and use a `while` loop to trace our way down the structure:

```javascript
const arr = [];
let head = linkedList;

while (head !== null) {
  arr.push(head.val);
  head = head.next;
}

console.log(arr);
// [5, 3, 10]
```

# How This Works

So how does this work? At each iteration of the `while` loop, the `head` variable points to one object deeper in the linked list.

```javascript
const linkedList = {
  // head @ Loop 1
  val: 5,
  next: {
    // head @ Loop 2
    val: 3,
    next: {
      // head @ Loop 3
      val: 10,
      next: null,
    },
  },
};
```

Each loop we push the `val` to our `arr` and then move on. If `next` is `null`, our `while` loop ends!
Implementing Design Patterns in Java
Tags: design, java
Published: 2020-05-06 11:52:19


The Design Patterns Book by the Gang of Four revolutionized programming with respect to designing Java Code. I tinkered with the concepts given in the book and posted on each of the design patterns here with use cases implemented in Java. This is one of the series in my current 100 Day project of posting one post per day for 100 days:
https://fullstackdeveloper.guru/design-patterns/
My new npm package RademeJs
Tags: rademejs, showdev
Published: 2020-05-06 11:29:13

Howdy world,  today I am excited to recommend you to this wonderful npm package called [rademe-js](https://www.npmjs.com/package/rademe-js "JavaScript helper library").

I created this package to help professional developers and beginners as well to stop repetitive tasks and use each features of the language wisely.

## Problems 
Many at times you will want to loop through an array or an object, it may also be a way to check the type of each data types or maybe to create a html element or some cool helper methods that you keep on repeating yourselves.

These things have happened to me at my job and I decided that why not make each helper methods into a reusable code or function that I can use in whatever project I am doing and this started to get great and I enjoyed those moments.

Now I have decided to make these simple helper methods available to every one and am open to  contributions.

There are some cool helper methods you find in this package that you will add to your project for fast development.

I will love to hear what you think about this project and what new features should be added or if you find a bug my DM is always open or contact me through my mail cnah27@gmail.com

Happy Coding,
Have an awesome day
Firebase Firestore unit testing with jest (and kind of typescript)
Tags: typescript, unittest, firebase, firestore
Published: 2020-05-12 19:23:35

---
title: Firebase Firestore unit testing with jest (and kind of typescript)
published: true
date: 2020-05-06 11:29:01 UTC
tags: typescript,unittest,firebase,firestore
canonical_url: https://medium.com/@efishtain/firebase-firestore-unit-testing-with-jest-and-kind-of-typescript-e26874196b1e
---

### It took some time but I think I got it

![](https://cdn-images-1.medium.com/max/1024/0*MfR1D7dDKsguQFBU)<figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>

I was working the other day on a firebase project. The project is written using typescript, which is nice. It is basically a set of cloud functions which interacts with a Firestore database, among other things.

I wanted to write unit tests and I wanted the tests to run as fast as possible without any dependencies on a real Firestore instance — so I had to mock the Firestore calls.

Fair enough, should be easy… Well….

I wasted so much time trying to mock the complex structure of Firestore types, using way too many Firestore internal data structures when I decided that I must be wrong. If it is hard to mock — you are doing it wrong.

Let’s say I want to mock an update call on a document.

```
await collection('myCollection')
            .doc('myDoc')
            .update({ updated:true});
```

I have to mock three functions - collection, doc and update on the firestore instance i’m using. So if I’ll try to do something like this:

```
import \* as admin from 'firebase-admin';

let update = jest.fn()
let doc = jest.fn(()=>({update})
jest.spyOn(admin.firestore(), 'collection').mockReturnValue({ doc });
```

The compiler does not like it, it says:

```
Argument of type ‘{ doc: any; }’ is not assignable to parameter of type ‘CollectionReference<DocumentData>’.
 Type ‘{ doc: any; }’ is missing the following properties from type ‘CollectionReference<DocumentData>’: id, parent, path, listDocuments, and 16 more.
```

Problem is, I don’t really need most of the functionality of a Firestore collection object or a document object, so I don’t want to waste time mocking it.

**The solution, is pretty straightforward, don’t mock what you don’t need.**

Just make the return value an unknown type, and then make it any type. It’s kind of anti typescript, but for mocking external dependencies I think I can live with that.

```
import \* as admin from 'firebase-admin';

const update = jest.fn();
const doc = jest.fn(() => ({update}));
const collection = jest.spyOn(admin.firestore(), 'collection').mockReturnValue((({ doc } as unknown) as any);
```

**voilà**!

I can now expect what ever I want on these mocks:

```
expect(collection).toHaveBeenCalledWith('myCollection');

expect(doc).toHaveBeenCalledWith('myPost');

expect(update).toHaveBeenCalledWith({updated:true});
```

Happy mocking!
Headless CMS — Integrating Gatsby with WordPress
Tags: wordpress, gatsby, javascript, graphql
Published: 2020-05-06 11:11:40


A headless CMS is a back-end content management system that allows content authoring, which delivers the content as data over a RESTful API instead of rendering a website.

Click the link below to learn more. 👇

https://medium.com/@ct.solutions/headless-cms-integrating-gatsby-with-wordpress-f68b0b8f163

We should always analyse the project specifications and goals when choosing a technology. If the emphasis is on scalability, performance, speed of development, long lifecycle and ability to make changes, fast headless WordPress is a good approach.

I didn’t believe the speed until I tried it myself. 😃
LeetCode: First Unique Character in a String
Tags: datastructures, algorithms, hashing, interview
Published: 2020-05-06 11:09:21

---
title: LeetCode: First Unique Character in a String
published: true
description: 05.05.2020
tags: datastructures, algorithms, hashing, interview
series: LeetCode May Challenge
---



### Problem Statement

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

### Example

```
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
```

**Note:** You may assume the string contains only lowercase letters.


### Solution Thought Process

This is a hash map problem. First, we count the frequency of the characters in the string by iterating over the string once. Then we iterate through the string again, this time if we find the frequency `1` of a character, we will set this as the answer and we break the loop. If no element's frequency which equals 1, we return `-1` as the answer.

### Solution

```c++
class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char,int> M;
        for(int i=0;i<s.size();i++)
        {
            if(M.count(s[i]))
            {
                M[s[i]]++;
            }
            else {
                M[s[i]] = 1;
            }
        }
        int answer_index = -1;
        for(int i=0;i<s.size();i++)
        {
            if(M[s[i]]==1)
            {
                answer_index = i;
                break;
            }
        }
        return answer_index;
    }
};
```




### Complexity

**Time Complexity:** O(n), where n = length of s.

**Space Complexity:** O(n), where n = length of s.
Nginx configuration for Angular2+ Deployment
Tags: nginx, angular, configuration, 404
Published: 2020-05-06 11:08:57

## Quick note
Nginx is a high performance web server with some additional capabilities such as load-balancing and reverse-proxy.
Angular is one of the most popular framework for building single page applications.
Angular apps can be connected to a Node js server and deployed but in most cases deployment with a simple web server would be suffice.

Angular can use either of the two routing strategies:
* Hash Routing
* Path Routing (default for Angular)

Path Routing utilizes the new HTML 5 push state API for routing. Therefore we need a web server capable of working with the HTML 5 push state API.Well most web servers don’t work this way out of the box. In these cases the hash routing strategy can be used, but tends to make the URL look messy. Nginx can be configured to deploy any Angular App with HTML 5 push state API.
Build your Angular app by using the command

``` 
ng build --prod 
```
Create a new folder under /var/www , usually the domain name of your app, let us assume to be example.com
```
sudo mkdir /var/www/example.com
```
copy the contents /dist/appname to /var/www/example.com

Nginx utilizes server blocks to host multiple domains on an single server, you to need to make certain changes to the configuration file
```
sudo nano /etc/nginx/sites-enabled/default
```

Add the configuration
```
server{
    listen 80;
    listen [::] 80;
    server_name www.example.com example.com;
    root /var/www/example.com;
    index index.html;
    location / {
        try_files $uri$args $uri$args/ /index.html;
    }
}
```
The configurations are:
* Nginx listens on port 80
* server name is the domain name with www and without it
* root points to location of the app
* index points to initial page to be loaded
* location refers path that should be pointed to on the url patterns, all routes will point to index.html, if this is not added, on refreshing the page Nginx throws a 404 error.
* Note: Use wildcard route pattern in angular to catch 404 errors
```
const routes: Routes = [
{path:"**",component: PagenotfoundComponent}
];
```

Restart Nginx
``` 
sudo service nginx restart 
```
Happy coding !!
Node.js Vs Django
Tags: django, node, javascript, python
Published: 2020-05-06 11:08:02

It is essential to select the appropriate programming language while building a project or developing an app. Every project comes with various specifications and requirements, and therefore, one ought to code it with the correct technology.

While comparing Node.js web framework and Django web app development program, selecting a backend technology happens to be one of the most significant issues which need to be fixed prior to opting for a development project.

In this article, we will remain neutral while selecting the winner by evaluating the pros and cons of both the programming languages such that you will be able to choose the appropriate one for your project.

Comparing Node.JS and Django can be difficult since both happen to be fundamentally different languages. While Django can be considered to be a Python web framework Node.JS is actually a library intended for JavaScript. Even though both of them happen to be open-source, which one you ought to learn first? Let us try to find that in this Node.JS vs Django review.

Let's see here, we have highlighted some of the most significant differences between the two languages.

https://hopinfirst.com/nodejs-vs-django-which-is-better/
LeetCode: Ransom Note
Tags: datastructures, algorithms, interview, hashing
Published: 2020-05-06 10:38:50

---
title: LeetCode: Ransom Note
published: true
description: 03.05.2020
tags: datastructures, algorithms, interview, hashing
series: LeetCode May Challenge
---

### Problem Statement

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

### Example

**Note:**
You may assume that both strings contain only lowercase letters.

```
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
```



### Solution Thought Process

This is a well known hash map problem.

- Find the frequency of each element in the magazine, store them in a hash map.
- For each element in the ransom note, check the value in the map.
  - If it doesn't exist, we can't make the ransom note.
  - If it exists, then check if it's unused frequency is greater than 0.
    - If it's greater than 0, then decrease the frequency to use it in the ransom note.
    - If it's not greater than 0, then we have used up all of the characters available in the magazine, so we should return false.

### Solution

```c++
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char,int>M;
        bool result = true;
        for(int i=0;i<magazine.size();i++)
        {
            if(M.find(magazine[i])==M.end())
            {
                M[magazine[i]]=1;
            }
            else {
                M[magazine[i]]++;
            }
        }
        for(int i=0;i<ransomNote.size();i++)
        {
            if(M.find(ransomNote[i])==M.end())
            {
                result = false;
                break;
            }
            else 
            {
                if(M[ransomNote[i]]>0)
                {
                    M[ransomNote[i]]--;
                }
                else {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }
};
```



### Complexity:

**Time Complexity:** O(m + n), where m = length of magazine and n = length of ransom note

**Space Complexity:** O(m) where m = length of the magazine


##
Can someone explain that logic to me? 
Tags: Help, Javascript, Logic
Published: 2020-05-06 10:36:11

Hi I'm following a Webdev Course on udemy. As an exercise we had to identify a missing number from an array and so the solution was like this :

var numbers = [4, 8, 9, 12, 19, 7, 3, 15, 2, 17, 20, 1, 11, 5, 10, 13, 16, 14, 18]

function missingno(numbers){

var missing = - 1

  for (var i=0; i <= numbers. length; i++){

    if(numbers.indexOf(i) === - 
    1){
     missing = i
    }
  } 
  return missing
} 

console.log(missingno(numbers))

I don't understand why the index of the missing numbers is - 1. Is it a rule? or is there a mathematical logic to it? And if so, what would be that logic?

My brain is smoking right now. 

If anyone can take the time to explain, it would be greatly appreciated.

Peace!
LeetCode: Jewels and Stones
Tags: datastructures, algorithms, interview, hashing
Published: 2020-05-06 10:25:11

---
title: LeetCode: Jewels and Stones
published: true
description: 02.05.2020
tags: datastructures, algorithms, interviews, hashing
series: LeetCode May Challenge 
---

###  Problem Statement

You're given strings `J` representing the types of stones that are jewels, and `S` representing the stones you have. Each character in `S` is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in `J` are guaranteed distinct, and all characters in `J` and `S` are letters. Letters are case sensitive, so `"a"` is considered a different type of stone from `"A"`.

### Example

**Example 1:**

```
Input: J = "aA", S = "aAAbbbb"
Output: 3
```

**Example 2:**

```
Input: J = "z", S = "ZZ"
Output: 0
```

**Note:**

- `S` and `J` will consist of letters and have length at most 50.
- The characters in `J` are distinct.

### Solution Thought Process

This is a well-known hash problem. First, we take the jewel string and record the frequencies in the hash set. Then we go through the S string to find out if this is a jewel by checking the set one by one, increasing the count of the result by one.

We can find the items in the unordered_set in O(1) time.

### Solution

```c++
class Solution {
public:
    int numJewelsInStones(string J, string S) {
        unordered_set<char>jewels;
        int result = 0;
        for(int i=0;i<J.size();i++)
        {
            jewels.insert(J[i]);
        }
        for(int i=0;i<S.size();i++)
        {
            if(jewels.find(S[i])!=jewels.end())
            {
                result++;
            }
        }
        return result;
    }
};
```



### Complexity

**Time Complexity:** O(m+n) where m = length of J, n = length of S

**Space Complexity:** O(m) where m = length of J
LeetCode: First Bad Version
Tags: datastructures, algorithms, interview, binarysearch
Published: 2020-05-06 10:23:22

---
title: LeetCode: First Bad Version
published: true
description: 01.05.2020
tags: datastructures,algorithms,interviews,binarysearch
series: LeetCode May Challenge
---

### Problem Statement

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API `bool isBadVersion(version)` which will return whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

### Example

```
Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 
```

### Solution thought process

If you have to find the first occurrence of an element in a sorted array of some kind, binary search should be the first thing we should be thinking of. 

Let's think of the first scenario:

```
Scenario #1: isBadVersion(mid) => false

 1 2 3 4 5 6 7 8 9
 G G G G G G B B B       G = Good, B = Bad
 |       |       |
left    mid    right
```



If we can see that the **isBadVersion** is returning false for mid, we can adjust our `left` to be equal to `mid+1`, because we know that we don't have to consider previous [left, mid] region for the answer, as we can see it from the scenario #1.



```
Scenario #2: isBadVersion(mid) => true

 1 2 3 4 5 6 7 8 9
 G G G B B B B B B       G = Good, B = Bad
 |       |       |
left    mid    right
```

If we can see that **isBadVersion** is returning true for mid, we can adjust our right to be `mid-1` and our `result = mid` because we have to find the first occurrence of the bad product.






### Solution

```c++
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

class Solution {
private:
    int binarySearch(int t)
    {
        int L = 1, U = t, result = -1;
        while(L<=U)
        {
            int M = L + (U-L)/2;
            bool badVersionResult = isBadVersion(M);
            if(badVersionResult == true)
            {
                result = M;
                U = M-1;
            }
            else {
                L = M+1;
            }
        }
        return result;
    }
public:
    int firstBadVersion(int n) {
        return binarySearch(n);
    }
};
```




### Complexity

**Time complexity:**  O(logn), on every loop we are making the candidate space into half, giving it a logarithmic complexity.

**Space Complexity:** O(1), we are not assigning any additional array.
2. Installation of Java
Tags: Java, devops, introduction, beginners
Published: 2020-05-06 10:21:55

2.1. Recommended Java version
It is recommended to use last least the latest long-term release version of Java. Currently this is Java 11.

2.2. Check installation
To run Java programs, you:

must have the Java runtime environment (JRE) installed

the Java executables must be available in your path environment

You can test if the JRE is correctly installed via a console. To open a console on Windows: Win+R, enter cmd and press Enter). Now type in the following command:

java -version
If the JRE is correctly installed, this commands prints information about your Java installation. In this case you can skip the Java installation description.

If the command line returns the information that the program could not be found, you have to install Java.

2.3. Install Java
For Microsofts Windows, Oracle provides a native installer which can be found on the Java website (http://java.com/). It contains instructions how to install Java for all supported platforms.

Install Java on Ubuntu
On Ubuntu you can install Java 11 via the following command on the command line. These commands might change over time, if they do not work anymore please Google for the installation.

# in case you prefer the Oracle Java distribution
# you can alternatively use the following commands
sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt-get install oracle-java11-installer
2.4. Installation problems and other operating systems
If you have problems installing Java on your system, search via Google for How to install JDK on YOUR OS. Of course, replace YOUR OS with your operating system, e.g., Windows, Ubuntu, Mac OS X, etc. This should result in helpful links.
Build a Memory Game in vanilla JavaScript
Tags: javascript, womenintech, game
Published: 2020-05-06 10:12:14

Memory Game, also known as the Concentration card game or Matching Game, is a simple card game where you need to match pairs by turning over 2 cards at a time. 

In this walkthrough, I will be putting extra focus on setting Attributes in JavaScript. If you want to learn how to use setAttritube and getAttribute effectively, please do code along.

We are also going to be looking at:
* for loops
* addEventListener
* setAttribute
* getAttribute
* data-name
* document.querySelector
* createElement
* Sort 
* math.random.

As always I have kept the styling at a bare minimum for you to go wild and make it your own. 

I would love to see what you made so please tag me on twitter on @ania_kubow or mention me on Youtube so I can find it and see :)

{% youtube tjyDOHzKN0w %}
Handling errors with Fetch
Tags: fetch
Published: 2020-05-06 09:52:51

Enhancement of one of my previous post [Swiss&Fetch](https://dev.to/artydev/swiss-and-fetch-48pj).
Here is a way to handling errors when fetch fails

```js
async function fetchUsers(numUsers) {
    const response = await fetch(`https://randomuser.me/api/?results=${numUsers}`)
    return await response.json()
}

async function displayUsers(numUsers) {
    let data = await fetchUsers(numUsers).catch(e => console.log(e.message))
    data && listusers.setAttribute("users", JSON.stringify(data.results))
}
```