teleren/devto huggingface dataset:
Javascript Object Lookups
Tags: javascript, webdev
Published: 2019-07-08 19:04:11

Original post at [toncho.dev](https://toncho.dev/javascript-object-lookups)

---

We are going to see how object lookups can sometimes be used as a more maintainable alternative to if and switch statements.

---

### Swtich

The [`switch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) statement evaluates an expression, matching the value to a `case` clause, and then executes statements associated. What switch does is take input and provide an output based on the `case` clause.

```javascript
const type = 'apple';

let fruit;

switch(type) {
  case 'apple':
    fruit = 'Apple';
    break;
  case 'pear':
    fruit = 'Pear';
    break;
  default:
    fruit = 'Unknown fruit!';
    break;
}

console.log(fruit);
// expected output: "Apple"
```

There are many problems with `switch` statement, it has non standard way to handle code blocks, the rest of JavaScript uses curly braces but switch does not. We are forced to add `break` statements within each case, which can lead to difficult debugging, make mistakes when writing each `case` clause for often forget to add this `break` statement, also the number of `case` clause increases, the performance of the object gets better than the average cost of the switch where the order of the cases matter. The object approach is a hash table lookup, and the switch has to evaluate each case until it hits a match and a break.

---

### If and Else

The [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) and [`else`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) statements are similar to `switch`, but it evaluate a single value, if the specified condition is truthy the `if` statement executes otherwiese if the condition is falsy the `else` statements executes, when they are a lot of `else if` statements, something is really wrong and generally you should use something like `switch` as it’s more suited for the purpose and intention.



```javascript
const getFruit = (type) => {
  if (type === 'apple') {
    type = 'Apple';
  } else if (type === 'pear') {
    type = 'Pear';
  } else {
    type = 'Unknown fruit!';
  }

  return type;
}

const type = 'apple';

console.log(getFruit(type));
// expected output: "Apple"
```

---

### Object Lookups

We use Objects all the time, either as constructors or literals. We are going to get values from the Object properties.

```javascript
const getFruit = (type) => {
  return {
    'apple': 'Apple',
    'pear': 'Pear',
  }[type];
}

const type = 'apple';

console.log(getFruit(type));
// expected output: "Apple"
```

This example is mapping one value to another one. with the object lookup we provide a cleaner way to write the code, we don't have to worry about `case` clause or `break` statement and it's easier to read and quickly understand what's going on.
macOS Catalina to have zsh as default shell
Tags: catalina, zsh
Published: 2019-06-13 09:56:08

---
title: macOS Catalina to have zsh as default shell
published: true
description: macOS's Catalina to have zsh shell.
tags: Catalina, zsh
cover_image: https://thepracticaldev.s3.amazonaws.com/i/bt8skrp5fkun2suvt0tn.png
---
Apple's #WWDC2019 (Worldwide Developers Conference) was held on June 3-7.
macOS's next big upgrade will be called Catalina and with it comes a big change for developers.

By default macOS releases till now used bash as the default shell. New user accounts in macOS Catalina will have zsh as the default shell. Zsh is an open source shell very popular and comes with a ton of features.

Zsh is very popular in dev community and can be installed in pre Catalina macOS as well. Zsh and Iterm2 (https://www.iterm2.com) goes very well together and improve the developer productivity.
Can we make a better CSS?
Tags: discuss
Published: 2019-06-13 09:42:29

---
title: Can we make a better CSS?
published: true
tags: discuss
---

Now that the State of CSS results are in, I'm reminded of all the complaints I've had about CSS over the years.

Has anyone ever tried to write a more intuitive abstraction or DSL on top of CSS? 

I remember seeing little tools, like one that allows you to describe a CSS grid with pipes and dashes, but nothing comprehensive.

Better yet, is there anything that can turn natural-language queries into CSS?! That'd be a fun project, huh?
Learning (practical) Quantum Computing
Tags: quantumcomputing, tutorial, beginners, quantumprogramming
Published: 2019-06-13 09:35:18

I'm basically recording myself as I learn about Quantum Computing. 

I'm trying to learn it at an intuition / engineering / practical level rather than most of the academic material that's out there.

Hope it's helpful for others!

https://www.youtube.com/channel/UC-2knDbf4kzT3uzWo7iTJyw
Web Developers, what type of support to you offer your clients?
Tags: webdev, discuss, productivity, business
Published: 2019-06-13 09:21:37

---
title: Web Developers, what type of support to you offer your clients?
published: true
description: Let's talk about how we do ongoing support for clients...
tags: web development, discuss, productivity, business
---

I've found myself more and more in the situation where I need to offer some kind of monthly support plan to my ongoing clients. Up until now, I've always done things either ad hoc with hourly pricing, however it's getting to the point where I need to formalize this more.

Some ideas that I had as offerings were:

- Phone support hours with time limits
- Email support hours with time limits
- Uptime monitoring (leveraging a service like node ping) with SLA's for outages.
- Error monitoring (leveraging a service like sentry) with a set amount of hours for fixing critical bugs and errors and a discounted pro rate after exceeded.
- Managing their DNS and hosting
- Analytics reporting
- Lighthouse reporting with a set number of hours dedicated to making performance enhancements when applicable.
- Discounted hourly and project rates for all work of support plan subscribers.

Previously I didn't want all the headache that comes with hosting and managing websites. However, I've come around to the idea that I end up being the first call anyway when something goes wrong so it would be better to catch these things early and be empowered to just fix them. I also want to be fair with pricing and offer the most value so my recurring pool of customers stays happy.

I'd love to hear how other people have handled and/or priced this type of service. Do you add on monthly retainers? Do you allow rollovers? What are the pitfalls that one should absolutely avoid when doing this? Any horror stories?
Laravel PLogs
Tags: laravel
Published: 2019-06-13 09:02:35

Laravel package to save logs in database making them permanent, always available for as long as you want.

# Screenshot

![enter image description here](https://raw.githubusercontent.com/sarfraznawaz2005/plogs/master/screen.jpg)

* * *

**[Checkout Laravel PLogs](https://github.com/sarfraznawaz2005/plogs)**
Testing doctrine migration in Symfony project
Tags: php, symfony, doctrine, migrations
Published: 2019-06-13 08:23:20

---
title: Testing doctrine migration in Symfony project
published: true
description: A simple guide for testing doctrine migration in Symfony project using console.
tags: PHP, Symfony, Doctrine, Migrations
---

1. Checkout to the master branch 
`git checkout master`.

2. Update database to match current doctrine schema, also removing excess tables 
`php bin/console d:s:u --force --complete`, where `d:s:u` is automatic short version of `doctrine:schema:update`, provided by Symfony console.
> NB! It deletes all tables from the database that are not in doctrine schema!
If you want to keep some tables (migration table could also be removed), then run `php bin/console d:s:u --dump-sql --complete`
do display excess  tables, remove them manually and then run `php bin/console d:s:u --force` to make schema up-to-date with master.

3. Add all migrations`php bin/console d:m:v --all --add -n`
where `d:m:v` is automatic short version of `doctrine:migrations:version`, provided by Symfony console.

4. Checkout to your feature branch `git checkout KEY-123`

5. Run migrations `php bin/console d:m:m -n`, where `d:m:m` is automatic short version of `doctrine:migrations:migrate`, provided by Symfony console.
State of CSS Survey 2019 Results
Tags: css, webdev, frontend
Published: 2019-06-13 07:55:28

---
title: State of CSS Survey 2019 Results
published: true
description: 
tags: #css #webdev #frontend
---

*I’m just passing on news here*

The results for the State of CSS Survey that some of you may have taken have been compiled. 

[Here is the website](https://2019.stateofcss.com/)

There’s some very interesting things in there! Enjoy!
5 Mistakes I made Whilst Learning to Code
Tags: discuss, webdev, beginners, career
Published: 2019-06-13 07:45:36

---
title: 5 Mistakes I made Whilst Learning to Code
published: true
description: The mistakes I made in the code learning process and things I would do differently if starting again.
tags: #discuss #webdev #beginners #career
---

Looking back in hindsight is always a beautiful thing. Here are five of the biggest mistakes I think I personally made when learning to code, so you don’t fall for the same traps!


🌱 Not researching properly before starting - Not having a clear idea of what sort of technology interested me, to begin with, was a mistake. I didn’t understand what the languages all did, I didn’t know what a either a “full-stack” or “front-end” developer was and therefore couldn’t choose what I wanted to learn. This meant I took a few months before I then realised that web development and  Javascript was for me which wasted valuable time and effort in the process.


🚀 Not having a clear goal or plan - When I started, I just wanted to get “good at code”. I didn’t initially have a goal to work towards and I realise now that defining these targets to work towards massively boosts my productivity. 


👨‍🎓 Course swapping - Swapping between whatever course looked interesting seemed fun at the time, but it meant I was re-learning things I had already learnt and never implementing them into real-world applications and practising them. I always say you can't learn to play a musical instrument by reading sheet music, you need practical experience and to practice over and over.


😧 Skipping hard concepts - This one doesn’t need any explanation, but I would skip or gloss over hard concepts. Spending three months learning one concept will be better for you in the long run, even if it seems your progress has slowed! I have also found that not having an understanding at least to be able to explain some core concepts of web development will bite you in the ass. Initially, I was quite happy to just say "I'm just a doer. I can implement things but not explain how or why it is working." I still struggle with this to this day!


📈 Comparing my self to others - I learn fairly slowly, so comparing myself to others was a mistake as my confidence was often knocked! We all learn at different paces, so try not to track your progress against anyone else because it will likely end in tears!



What mistakes did you make whilst learning to code? Would you do anything differently if you were to start again?
What's the biggest problem you encounter when developing Dapp?
Tags: blockchain, webdev, dapp, ethereum
Published: 2019-06-13 07:43:05

I am wondering what's the main problem Dapp(Decentralized App) developers are facing. I have developed crypto wallet app for Dapp, and I hope I can do something to help them. I have already collected some:

1. Support many wallets(MetaMask, Ledger, Trezor, Mobile Wallets, Wallet Connect, etc.)
2. Ask users to install wallets
3. Manage user wallets by yourself(I see some Dapp don't like to use 3rd party wallet)
4. Support different chains(Ethereum, EOS, TRON, etc.)
5. Test and deploy smart contract
6. Other
The fascinating phenomena of PHP trashing????
Tags: beginners, php, node, discuss
Published: 2019-06-13 06:50:21

---
title: The fascinating phenomena of PHP trashing????
published: true
description: why trash talk PHP?
tags: #beginner #php #node #discuss
---
Navigating my way through this new and exciting world of writing code, I am facinated by PHP trash talk. It 'does what it says on the tin' as far as I can tell....  ??? Someone please enlighten me!

Is this like admitting you like Savage Garden...? Or have a pair of stonewash jeans? Or drive an Astra?

*** Disclaimer: I have no allegiance or impassioned viewpoint. Though I did once wear stonewash jeans and drive and Astra. But never listened to Savage Garden. Honest.
Using Netlify functions to fetch external files
Tags: lambda, netlify, fetch
Published: 2019-06-13 06:48:07

---
title: Using Netlify functions to fetch external files
published: true
cover_image: https://fabiofranchino.com/blog/assets/posts/using-netlify-lambda-function-to-load-externals/img.gif
tags: lambda, netlify, fetch
---

In my recent [side project](https://www.svgmator.com/), I had the need to load external files from within the browser, such as an SVG file hosted on a remote server, in order to inject them in the DOM for further manipulation.

It's a nice little UX add-on to avoid the user downloading a particular file and then to upload it on SVGmator. Providing the URL, the software would be able to download and upload behind the scene on behalf of the user.

It's a simple task, but the security model of the browser prevents to fetch, via javascript, external text files that belong to different domains, thus, this simple script is not going to work out of the box:

```javascript
fetch('https://www.examples.com/myfile.svg')
```

## Welcome Lambda Functions

It these days it's quite common to find services that provide the so-called lambda functions. Briefly, they are (usually Node.js) scripts that can be invoked through an API call, performing a task and returning a result. You don't have to deal with their hosting and other server stuff (indeed they are part of the serverless movement!).

Back to my problem, here the code that accomplishes the mentioned requirement, using [Netlify Functions](https://www.netlify.com/docs/functions/) in this case (the Netlify version of the lambda thing).

The browser needs to make a POST request to the lambda, passing a parameter, such as:

```javascript
const req = await fetch('/.netlify/getsvg', {
   method:'POST',
   body: JSON.stringify({url: 'https://www.examples.com/myfile.svg'})
})
const res = await req.text()
```

The above code (it's ES6, it needs to be within an async function) will get a raw SVG code that can be eventually injected in the DOM.

The lambda function is a Node.js script that actually fetches the SVG and returns it as raw source:

```javascript
const axios = require('axios')
    
exports.handler = async (event, context) => {
   const body = JSON.parse(event.body)
    
   const res = await axios.get(body.url)
    
   return {
      statusCode: res.status,
      body: res.data
   }
}
```

That's approximately all. Please refer to the [Netlify documentation](https://www.netlify.com/docs/functions/) about how to use the service.

This article has beed originally published on my [blog](https://fabiofranchino.com/blog/using-netlify-lambda-function-to-load-externals/).
react loop forms with validation
Tags: react
Published: 2019-06-13 05:46:25

I am creating one page in react which has Child details from other page. If I choose no of child has 5 then I need to display 5 child forms in the next page. and need to add validation for that child form. validation should happen dynamically for those 5 child forms. child form contains name, age, country and etc. kindly help me on this.
Transition from Beginner to Intermediate/Senior developer
Tags: discuss, productivity
Published: 2019-06-13 05:15:48

When do you think the transition from a beginner/noob developer to the next level takes place?

Specifically, when do you know you're on the verge of crossing that line where you think you're *upping* your game? ;)

Personally, I think it's when you stop worrying about the language you code in, but then care about **the design patterns, the paradigms, and the architecture!**

Because at the end of the day, it's about utilizing the right tool for the fit problem, isn't?
What 10 things can I do now to have a better life?
Tags: motivation, life
Published: 2019-06-13 03:40:04

---
title:What 10 things can I do now to have a better life?
published: true
description:What 10 things can I do now to have a better life?
tags: #motivation, #life
---

1) Start reading <a href="https://fullstackgeek.blogspot.com/p/must-reads.html">books</a>

2) Start Financial Planning.

3) Daily Workout/walk for at least 30 minutes.

4) Stay away from “deals” which robs you of money directly or indirectly.

5) Start Writing on whatever topics you like.

6) Start Listening other’s points too even if you don’t agree with them.

7) Focus on Skill Development.

8) Donate food/clothes to the poor, it would really motivate you.

9) Start thinking of 2nd hand income ASAP.

10) Stay away from Social Media and read Indian Express.

Hugs,

Full Stack Geek
How old were you when you wrote your first line of code?
Tags: discuss, askdev
Published: 2019-06-13 03:28:19

---
title: How old were you when you wrote your first line of code?
published: true
description: How old were you when you wrote your first line of code?
tags: discuss, askdev
---

And maybe tell us what you wrote? :smiley:

I started at around 15-16 in High School and if I remember correctly it was a little bit of HTML that we wrote 😊
Simple web server in Perl and Go, Finally
Tags: webdev, go, html, performance
Published: 2019-06-13 03:02:12

---
title: Simple web server in Perl and Go, Finally
published: true
description: website performance based on implementation of Perl or Go
cover_image: https://i.stack.imgur.com/zBz23.png
tags: webdev,go,html,performance
---

OK, where were we and why we are here?

Quoting from [my blog](https://dev.to/suntong/simple-web-server-implemented-in-perl-and-go-b43/) that started all these:

> Back in my mind, I had always thought that Perl is slow, comparing to compiled languages, like C/C++. So it is always in my mind that I should rewrite my simple web server from Perl to a compiled language. Finally I did...

and the result was Perl performs better than Go, two times that I tried & blogged: [1](https://dev.to/suntong/simple-web-server-implemented-in-perl-and-go-b43/) & [2](https://dev.to/suntong/simple-web-server-in-perl-and-go-revisit-5d82/). 

The Go community was not very happy about it, and neither do I, as a matter of fact, because I _do_ believe that Go should be faster than Perl. Many people have given good & valid inputs as where things might get
improved, and I did try out everyone's suggestion to see how things can improve, including [avoiding regular expressions](https://github.com/suntong/dbab-go/commit/ef71bd5c9e57adc927da382cff6f9292a8006075), or [using the high performance web framework echo](https://github.com/suntong/dbab-go/commit/6bff4f88ac17ff37a5f453847b49e1e759e15baf#diff-b3f5741ecc18ac9b58d3e7efcb15901b) ([including echo v4](https://github.com/suntong/dbab-go/commit/bc4ec1969b2af64c876ad7c5be72e4ba862792c3#diff-b3f5741ecc18ac9b58d3e7efcb15901b)), but all are just marginally faster, or have no obvious benefit at all, in which case I didn't even log a version. 

That was quite some hectic journey, but long story short, I finally made it, with helps I got from various sources -- I finally [made Go faster than Perl](https://github.com/suntong/dbab-go-log/blob/660f1401fd70ae2846c40060b0758d078410c77a/dbab-svr/main.go)!!!

And here are the test results from my machine (which I [published here](https://gist.github.com/suntong/0900ba24566df5b4246dde9567f1d4fd)):

100 concurrency requests (the number of multiple requests to perform at a time):

![GoPerl](https://img.vim-cn.com/45/1f65fecf311abb97f9c51127ba41ac25ff1202.svg "GoPerl")

From this we can see Go is on-par with Perl for the ballpack of the results. OK, then why I said Go is now faster than Perl? 

Take a look at the Apache Bench's statistics first:

For Perl:

{% gist https://gist.github.com/suntong/0900ba24566df5b4246dde9567f1d4fd file=Perl.md %}

For Go:

{% gist https://gist.github.com/suntong/0900ba24566df5b4246dde9567f1d4fd file=FastHTTP.md %}

I.e., for the Requests per second (#/sec), Perl is `4450.18` while Go is `11675.42`. That's 2.6 times of Perl's throughput, while not sacrificing individual's response time much. 

Moreover, when the load is light (< 70), which is the most common situation for my specific case, Go is faster than Perl. 

So I'm quite happy with the result now.
Do you use tools to manage your schedule?
Tags: discuss
Published: 2019-06-13 02:48:42

---
title: Do you use tools to manage your schedule?
published: true
tags: discuss
---

I'm finding myself busier than ever and would love to hear what tools you use to keep yourself organized. When I was in college, I used Google Calendar for project group meetings and a paper planner for keeping track of when assignments were due.

If you have any pictures to share of your setup, I'd love to see those too! It's intriguing how differently everyone does the same thing. 🤓

---

Did you know I have a newsletter? 📬

If you want to get notified when I publish new blog posts or make major project announcements, head over to [https://ashleemboyer.com/newsletter](https://ashleemboyer.com/newsletter).
JavaScript: So class is a function?
Tags: javascript, beginners, class
Published: 2019-06-13 01:56:28

I have written a lot of class component using React. But I have never really understood class.
In this short post I will explore what class is fundamentally.

<br>

Lets go ahead & see one way to declare a class:

```javascript
class User {}
```

Here we use a class declaration to declare a class called User. So what is class? is it a function? or is it an object? Lets test:

```javascript
typeof(User) // "function"
```

Well __class is actually a function!__ 
If its a function, lets try to invoke it and see what happens.

```javascript
User() //TypeError: class constructors must be invoked with |new|
```

Eror! What happened? Initially we saw that class is a function, but when we tried to execute it like a normal function, it throws an error saying *class constructors must be invoked with |new|*.

<br>

#### Classes are "special functions"
According to MDN Classes are "special functions". I went to look for more info and learned that __class is actually used as a constructor function__. A constructor function is a function that is used to construct an object. That's why the console throws an error about needing the *new* keyword. In order to invoke a constructor function, we must use the *new* keyword.

Lets see an example:
```javascript
const lily = new User()

typeof(lily) // "object"

console.log(lily) // Object {}
```

We invoked the class using the new keyword and assign it to a variable named *lily*. When we evaluate the typeof *lily*, we got object as the result. The result from logging the value also returns an object. As mentioned above, constructor function generates an object. 

<br>

Im only scratching the surface here. In the future post I will explore even further on what goes inside class and why to use class when we can just use a normal function as a constructor function to construct an object.