teleren/devto huggingface dataset:
Avoid boolean values comparison with "==" in JavaScript
Tags: javascript, webdev
Published: 2018-04-14 03:22:51

---
title: Avoid boolean values comparison with "==" in JavaScript
published: true
description: 
tags: JavaScript, Web Development
---

All of us use "==" daily for performing the comparison in JavaScript to execute particular code block only when certain condition meets.

But do you know how "==" actually works in JavaScript?

In JavaScript "==" compare number values instead of boolean values by performing implicit coercion.

Here is a simple example : 

```javascript
 const a = 10;

 if(a == "10"){
     console.log("Woo! Condition is true.");
 }

```

*In above block of code we're comparing string value of <b>"10"</b> with a integer value of const variable <b>a</b> which is 10.<br>So here, JavaScript will first perform implicit coercion on non-number type value i.e. <b>"10"</b> and will convert it into a number and then perform comparsion.*


<h4>Why you should avoid comparison of boolean values with "=="?</h4>

We are now aware of the fact that <b>"=="</b> compare integer value type not boolean type.So comparing boolean values with <b>"=="</b> will not give desired result to you every time.

<h4>Examples of Wrong Implementation for value check :</h4> 
 
_Example 1_

{% runkit %}
 
    const a = 10;

    if(a == true){
        console.log("Condition is true.");
    }else{
        console.log("Condition is false.");
    }
 
 
{% endrunkit %} 

<i>Number equivalent of <b>true</b> is 1.<br> **False** : 10 is not equal to 1.</i>


_Example 2_

{% runkit %}
 
    const a = "1";

    if(a == true){
        console.log("Condition is true.");
    }else{
        console.log("Condition is false.");
    }
 
 
{% endrunkit %} 

<i>Number equivalent of <b>true</b> is 1 and <b>a</b> is 1.<br>**True** : 1 is equal to 1.</i>


<h4>Examples of Correct Implementation for value check :</h4> 
 
_Example 1_

{% runkit %}
 
    const a = 10;

    if(a){
        console.log("Condition is true.");
    }else{
        console.log("Condition is false.");
    }
 
 
{% endrunkit %} 

<i>**True** : Because the boolean equivalent of **a** is true.</i>


**_Example 2_**

{% runkit %}
 
    const a = "1";

    if(a){
        console.log("Condition is true.");
    }else{
        console.log("Condition is false.");
    }
 
 
{% endrunkit %} 

<i>**True** : Because the boolean equivalent of **a** is true.</i>


_Example 3_

{% runkit %}
 
    const a = "";

    if(a){
        console.log("Condition is true.");
    }else{
        console.log("Condition is false.");
    }
 
 
{% endrunkit %} 

<i>**False** : Because the boolean equivalent of **a** is false.</i>




<h2>Conclusion</h2>

Try to avoid using boolean values comparison with "==". It will work for you in many cases but it is not a right way to perform a condition check.
Testing REST API in VueJS
Tags: javascript, vue
Published: 2018-04-12 06:57:08

---
title: Testing REST API in VueJS
published: true
description: Testing REST API in VueJS
tags: #javascript #vue #vuejs #js
---

I've just started to work with `VueJS` on building prototypes of dashboard for my analytics works in the current company. `VueJS` is so simple that it became my favorite tool for building js apps. In `EmberJS` everyone is using mirage library to stub api calls and respond with the required bodies. In `VueJS` I've decided to archive the same behavior by using [vue-resource-mock](https://github.com/noru/vue-resource-mock) 

Lets push some examples there for easy understanding how to use this awesome library.

```javascript
// main.js
...
import VueResource from 'vue-resource'
import VueResourceMock from 'vue-resource-mock'
import MockData from './mock/data.js'

Vue.use(VueResource)

if (process.env.NODE_ENV === 'development') {
  Vue.use(VueResourceMock, MockData)
}
...
```

```javascript
// mock/data.js

const id = () => Math.floor(Math.random() * 100)

export default {

  ['GET */example'] (pathMatch, query, request) {
    let body = {
      collection1: [
        { id: id(), name: 'name1' },
        { id: id(), name: 'name2' },
      ]
    }

    return {
      body: body,
      status: 200
    }
  }
}
```

And finally if you have component where you are using http resource to get the data it should be the same as before, no changes required, just call http request and you will get mocked data.

```javascript
...
 
      this.$http
        .get(`${process.env.API_HOST}/example`)
        .then(response => {
          let { collection1 } = response.body
          this.$store.commit('setCollection1', collection)
        })
...
```
Hit a wall with AJAX basics
Tags: ajax, javascript, xampp, discuss
Published: 2018-04-08 06:55:20

---
title: Hit a wall with AJAX basics
published: true
description: Question about using AJAX locally on XAMPP server with Javascript
tags: AJAX, Javascript, XAMPP, discuss
---

I want to learn netcode for Javascript games and my googling lead me to AJAX.  I tried an example that pulled text from a .txt file and displayed it in an HTML paragraph, but it didn't work at all for me.

After quitting in frustration (I think I might have ADHD), I came back and googled some more, and it turned out my problem was that Chrome doesn't allow local AJAX calls.  It was recommended to install XAMPP and try again.

I don't have a lot of experience with Apache or XAMPP, but I have worked on web pages before so I was a little bit at-home with the basic folder system.  I created a http/ folder and placed my index.html, main.js code, and simple .txt file in it.  When I tried to run the code from the server, it gave me a different error.

Another bout of frustration hit me but I came back.  I returned to google and I found references to CORS and Comet, which I don't 100% understand, but I did glean that the file in question (the .txt file) needed a header.  But the problem is .txt files don't really have headers as they are just text and not read as code files.  Also, just about everything I could find mentioned adding the header to a PHP file, which isn't relevant for me because I'm using Javascript.  I tried adding the header to my .js file for just in case but that did nothing.

Does anyone here have any suggestions for how I can get this simple AJAX code to run locally on my computer so I can move on with my learning objective?  Thank you for your time!
Write a function that outputs a pleasant text color hex given a background color hex
Tags: challenge
Published: 2018-04-13 21:29:27

---
title: Write a function that outputs a pleasant text color hex given a background color hex
published: true
description: 
tags: challenge
---

"Pleasant" means a high enough contrast for reading, but also might include colors that don't clash with one another.

Do your best. No harsh judgement. 😝

Any languages/approaches welcome.
BigCommerce – Creating a WebHook
Tags: net, api, bigcommerce, c
Published: 2018-05-05 23:16:15

---
title: BigCommerce – Creating a WebHook
published: true
tags: .NET,API,BigCommerce,C#
canonical_url: 
---

I couldn’t find any reliable C# examples on how to create a webhook using BigCommerce’s API so I thought I’d share my solution. The example code below will create a webhook when an order is created in your BigCommerce store.

```
//BigCommerce Authorization
string clientID = "<your_client_id>";              
string token = "<your_token>";
string storeHash = "<your_store_hash>";
string resourcePath = "hooks";

string baseURL = "https://api.bigcommerce.com/stores/" + storeHash + "/v2/" + resourcePath;
                
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
               
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseURL);
req.AllowAutoRedirect = true;
req.ContentType = "application/json";
req.Accept = "application/json";
req.Method = "POST";

req.Headers.Add("X-Auth-Client", clientID);
req.Headers.Add("X-Auth-Token", token);             
      
//send scope and destination as json
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
    string json = "{\"scope\":\"store/order/created\"," +
                  "\"destination\":\"https://app.example.com/orders\"}";

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

string jsonResponse = null;
using (WebResponse resp = req.GetResponse())
{
    if (req.HaveResponse && resp != null)
    {
        using (var reader = new StreamReader(resp.GetResponseStream()))
        {
            jsonResponse = reader.ReadToEnd();
        }
    }
}

Response.Write(jsonResponse);
```
Falsy Values are N0 FUN!
Tags: javascript, beginners, tips, learning
Published: 2018-04-13 18:05:58

---
title: "Falsy Values are N0 FUN!"
published: true
description: "A simple mnemonic device to remember falsy values in JavaScript."
tags: javascript,beginners,tips,learning
cover_image: https://i.ytimg.com/vi/F6-jOmClEOk/maxresdefault.jpg
---

When I was a Latin teacher, I used to love coming up with mnemonic devices to help students remember novel or difficult things, like the order of the Roman kings, or the endings of verbs. But as I think about it, it's a technique I use for myself all the time.

Example: I just came up with a simple mnemonic device to remember the [falsy values](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) in JavaScript.

## falsy values == N0 FUN

**N0:**
- NaN
- 0 or -0 or "" (empty string, i.e., String.length === 0)

**FUN:**
- false
- undefined
- null

Now, this doesn't mean that YOU can't enjoy falsy values. You may think they're just as [fun, fun, fun, fun, FUN! as kazoo](https://www.youtube.com/watch?v=cRpdIrq7Rbo), but just as **Every Good Boy""** *doesn't necessarily* **Do Fine**, remember: **falsy values are N0 FUN.**
ESlint with Class Decorator
Tags: javascript, react, mobx, eslint
Published: 2018-04-13 15:03:30

---
title: ESlint with Class Decorator
published: true
description: 
tags: javascript, react, mobx, eslint
---

When I create a function which returns a Decorator attached class, ESLint cause an error.

We can write such function like this:

```jsx
// RequireLogin.js(error)
// @flow

import React from 'react'

@inject('userStore')
@observer
export default (ComposedComponent: *) => class RequireLogin extends React.Component<Props> {
  render() {
    if (this.props.userStore.guest) return <div>LOGIN REQUIRED</div>
    else return <ComposedComponent />
  }
}
```

`babel-plugin-transform-decorators-legacy` can transform it as expected, but ESLint raise Syntax Error.

To pass ESLint, the code should be like this:

```jsx
// RequireLogin.js(fixed)
// @flow

import React from 'react'

export default (ComposedComponent: *) => {
  @inject('userStore')
  @observer
  class RequireLogin extends React.Component<Props> {
    render() {
      if (this.props.userStore.guest) return <div>LOGIN REQUIRED</div>
      else return <ComposedComponent />
    }
  }

  return RequireLogin
}
```

BTW, this HOC is simple to use:

```jsx
// Home.js
// @flow

import React from 'react'
import RequireLogin from './RequireLogin'

@RequireLogin
export default class Home extends React.Component<Props> {
  render() {
    return <div>Hello</div>
  }
}
```

This HOC returns referring to injected MobX's store.

- When login user -> composed component
- When guest user -> login component

ref: https://github.com/yannickcr/eslint-plugin-react/issues/419
Don't ALWAYS quick-return from functions
Tags: functions, refactoring, cleancode, quickreturn
Published: 2018-04-13 13:17:50

---
title: Don't ALWAYS quick-return from functions
published: true
canonical_url: https://blog.benwinding.com/dont-always-quick-return-from-functions/
description: A brief look at the history behind the opposing styles of quick-return and single-return in functions.
cover_image: https://i.imgur.com/IV0f3CX.jpg
tags: functions, refactoring, cleancode, quick-return
---

There are two main styles of returning from a function in a program. Both styles are almost diametrically-opposed, but have their uses.

### Single Return
An example of nested single-returning. This is hard to read and keep track of the levels of scope.

``` c
int GetCost(request) {
    int cost = 0;
    if (request.Important) {
        if (request.HasDiscount) {
            if (request.IsMember) {
                cost = 10;
            }
            else {
                cost = 12;
            }
        }
        else {
            cost = 14;
        }
    }
    else {
        cost = 20;
    }
    return cost;
}
```

### Quick Return
Now arguably the code can be made simpler by using the prophetic "Quick Return!" method. This has the effect of returning out of the function as soon as possible, making the code easier to reason about. Also, by unravelling the if-statements into a neat stack, the code becomes much easier to read.
 
``` c
int GetCost(request) {
    if (!request.Important) 
        return 20;
    else if (!request.HasDiscount) 
        return 14;
    else if (!request.IsMember) 
        return 12;
    else
        return 10;
}
```

# However ... Memory Leaks
The reason quick returns were not encouraged in earlier days of programming is a lack of garbage collection. During the execution of a function, memory may be allocated. So a simplify this, the function is given only one exit point, to ensure all memory in the function is deallocated before the function returns. 

The following is another version of the single return function (with an added checking object). Cleaner and easier to read with still one return statement (and a little clean up).

``` c
int GetCost(request) {
    Checker checker = new Checker(request);
    int cost = 0;
    if (!checker.Important) 
        cost = 20;
    else if (!checker.HasDiscount) 
        cost = 14;
    else if (!checker.IsMember) 
        cost = 12;
    else 
        cost = 10;
    delete checker;
    return cost;
}
```

But memory might not be the only thing that needs to be cleaned up at the end of a function's execution. There are other things that might need to be 'freed up' like:

- Hardware resources
- Object mutation locks
- Network connections

By returning only once within a function, the chance of leaving one of these resources open/locked is greatly reduced.

So, the older method of single return is not completely useless! And depending on the language and environment, quick-returns may not always be the best solution.
webassembly
Published: 2018-03-08 07:43:03

---
title: webassembly
published: true
tags: 
canonical_url: https://tilde.team/~ben/blog/webassembly.html
---

according to [this post](https://hacks.mozilla.org/2018/01/making-webassembly-even-faster-firefoxs-new-streaming-and-tiering-compiler/) on the mozilla blog, we will be able to compile wasm as it streams into the browser in much the same way that images are decoded. this is a huge game changer from the current paradigm of loading javascript completely before being able to parse and compile it.

> JavaScript code is much more expensive, byte for byte, than an image, because of the time spent parsing and compiling it.  
>   
> It's possible to parse and compile wasm as fast as it comes over the network, which makes it much more like an image than JavaScript code.  
>   
> Game changer!
> 
> — Yehuda Katz (@wycats) [December 19, 2017](https://twitter.com/wycats/status/942908325775077376?ref_src=twsrc%5Etfw)

<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

this will make [so many things](https://github.com/WebAssembly/design/blob/master/UseCases.md) possible in the browser that never were before!

i decided to follow this [tutorial](http://webassembly.org/getting-started/developers-guide/) and ended up with [this](https://tilde.team/~ben/wasm/hello.html).

i don't know what to do next. any ideas?

Tags: [wasm](tag_wasm.html), [dev](tag_dev.html), [internet](tag_internet.html)

<!-- text end -->

[Comments? Tweet](http://twitter.com/intent/tweet?url=https://tilde.team/~ben/blog/webassembly.html&text=<Type%20your%20comment%20here%20but%20please%20leave%20the%20URL%20so%20that%20other%20people%20can%20follow%20the%20comments>&via=nebsirrah)
onappinstalled - for when an app is installed.
Tags: pwa, javascript
Published: 2018-04-13 21:08:55

---
title: onappinstalled - for when an app is installed.
published: true
tags: pwa, javascript
canonical_url: https://paul.kinlan.me/onappinstalled/
---

Chrome has recently (well at least in [2017](https://crbug.com/621393)) implemented `window.onappinstalled`[event](https://developer.mozilla.org/en-US/docs/Web/API/Window/onappinstalled). It is triggered when a user installs a progressive web app either via the Add to Homescreen API (the prompt() function on the event delivered via the`onbeforeinstallprompt` event) _or_ now more importantly via the manual method of Add to Homescreen.

This is a very useful addition because it allows you to see engagement on the prompt vs people who use the system banners or menu buttons to install a progressive web app.

I’ve added it to [Airhorner](https://airhorner.com) so you can see it in action if DevTools is attached. The code is below that manages `onbeforeinstallprompt`and `onappinstalled` - in this case I use onbeforeinstallprompt to defer the install prompt to a custom button, and `onappinstalled` to clean up the UI and do some basic analytics.

```
const Installer = function(root) {
  let promptEvent;

  const install = function(e) {
    if(promptEvent) {
      promptEvent.prompt();
      promptEvent.userChoice
        .then(function(choiceResult) {
          // The user actioned the prompt (good or bad).
          // good is handled in 
          promptEvent = null;
          ga('send', 'event', 'install', choiceResult);
          root.classList.remove('available');
        })
        .catch(function(installError) {
          // Boo. update the UI.
          promptEvent = null;
          ga('send', 'event', 'install', 'errored');
          root.classList.remove('available');
        });
    }
  };

  const installed = function(e) {
    promptEvent = null;
    // This fires after onbeforinstallprompt OR after manual add to homescreen.
    ga('send', 'event', 'install', 'installed');
    root.classList.remove('available');
  };

  const beforeinstallprompt = function(e) {
    promptEvent = e;
    promptEvent.preventDefault();
    ga('send', 'event', 'install', 'available');
    root.classList.add('available');
    return false;
  };

  window.addEventListener('beforeinstallprompt', beforeinstallprompt);
  window.addEventListener('appinstalled', installed);

  root.addEventListener('click', install.bind(this));
  root.addEventListener('touchend', install.bind(this));
};
```
An underwhelming, but exhilarating, first Leaf SDL-GL pipeline
Tags: graphics, leaf, compiler, coding
Published: 2018-04-13 09:06:39

---
title: An underwhelming, but exhilarating, first Leaf SDL-GL pipeline
published: true
description: First steps towards something visually useful in Leaf.
tags: graphics, leaf, compiler, coding
cover_image: https://thepracticaldev.s3.amazonaws.com/i/54ht02yy7tp8gih08bd2.png
---

It may not be pretty, but this represents a significant step forward in the Leaf  project. Enough to start [live game programming](https://www.twitch.tv/mortoray) -- follow me there to watch.

{% youtube CPOxLrps3oA %}

Points of interest:
- This demo is written in Leaf. You can see the, still somewhat scary, main file [over here](https://github.com/mortoray/leaf-algorithms/blob/master/sdl/gl_demo/main.leaf).
- I'm using libSDL2 to create the window and initialize OpenGL.
- It does handle window and keyboard events, this required some compiler changes to support the SDL C-union types (needed an unsafe `cast｢T｣(expr)` operator).
- I'm using GL vertex and fragment shaders with just a couple of vertex attributes and uniforms.
- Sending data to GL required an introduction of a `array.raw_ptr` member to get raw access to memory addresses in Leaf.
- I fixed numerous bugs in the compiler, including many improved error messages. Though "duplicate-symbol" reporting is still an issue (no location!).
- Fixed a rather major `alloca` issue that caused memory exhaustion. Otherwise this appears to be perfectly stable now.

This sets me up to start doing minimal games programming on [my stream](https://www.twitch.tv/mortoray). My goal is to explore some of the algorithms I'm using on the Evening Rust stream, expand the language, and have some fun while doing it.  It'll be a rough journey, but you're welcome to join!
AWS S3 Functionalities
Tags: aws, s3, node, showdev
Published: 2018-04-13 06:43:47

---
title: AWS S3 Functionalities
published: true
description: It is an application which allows you perform S3 functionalities at ease.
tags: AWS,S3,NodeJS,showdev
---

Hi Guys,

I have always wondered how to store files to AWS S3 on the fly and how to manipulate them.Even though I found references to the same, It failed to provide me a satisfying answer. The quest for the simple solution leads me to my version.


Repo : https://github.com/sudarsan15/aws-s3-functions


Feel free to check out and let me know your feedback.

Thank you
How to show subcategories images in Prestashop's top menu
Tags: blog, prestashop, tutorials
Published: 2018-04-13 09:52:29

---
title: How to show subcategories images in Prestashop's top menu
published: true
tags: blog, prestashop, tutorials
canonical_url: https://www.prestasoo.com/blog/how-to-show-subcategories-images-in-prestashop-s-top-menu.html
---

![](https://www.prestasoo.com/images/stories/add-image-to-prestashop.root.gif)

Few months ago i wrote an article to share about the way to [show categories images on Prestashop Menu](https://www.prestasoo.com/blog/tutorial-how-to-show-the-image-on-prestashop-1-7-menu.html?utm_source=article&utm_medium=article&utm_campaign=subcategoriesimages "Show categories images on Prestashop Menu").

Then @Psdesigner and @Damien Belgacig asked me about the way to put subcategories images instead of main category's image. Sorry 2 guys, Disqus didn't tell me about your comments.

Well, as my previous article, if you edit ps\_mainmenu template file (ps\_mainmenu.tpl) and put the source code as my suggest, all categories images will be showed on [Prestashop Menu](https://www.prestasoo.com/prestashop-modules/soo-magic-menu.html?utm_source=article&utm_medium=article&utm_campaign=subcategoriesimages "Prestashop Menu Module"). In case you only want to allow subcategories images, we need to make some changes.

##First, make sure you uploaded subcategories images

Edit your subcategories and upload menu's image as my previous article. You can't show the images if you don't have at least one, right?


##Ok, this is the most important step.

You need to make sure the main category is the root menu, and the categories are the submenus. I don't have time to play with Prestashop default menu so i don't know can we setup a subcategory as a root menu or not (we have SOO Magic Menu - do you remember? We love it so much and hope people use it everyday :D).

Re-open your-website/themes/classic/modules/ps_mainmenu/ps_mainmenu.tpl file and find the code around line 27. 

Visit my page to explain how to play with your Prestashop website : https://www.prestasoo.com/blog/how-to-show-subcategories-images-in-prestashop-s-top-menu.html