Thursday, December 7, 2017

Map, Filter and Reduce In Javascript

map creates a new array by transforming every element in an array, individually.
filter creates a new array by removing elements that don't belong.
reduce, on the other hand, takes all of the elements in an array, and reduces them into a single value.

Suppose we have an app that maintains an array of your tasks for the day. Each task is an object, each with a name and duration property:
// Durations are in minutes
 
var tasks = [ 
  { 
    'name'     : 'Write for Envato Tuts+', 
    'duration' : 120 
  }, 
  { 
    'name'     : 'Work out', 
    'duration' : 60 
  }, 
  { 
    'name'     : 'Procrastinate on Duolingo', 
    'duration' : 240 
  } 
];

map in Practice

Let's say we want to create a new array with just the name of each task, so we can take a look at everything we've gotten done today.

Using map, we can write:
var task_names = tasks.map(function (task, index, array) { 
    return task.name; 
});

// Using ES6 arrow functions
 var task_names = tasks.map((task) => task.name );

filter in Practice

The next of our array operations is filter. It takes an array, and filters out unwanted elements. Let's revisit our task example. Instead of pulling out the names of each task, let's say I want to get a list of just the tasks that took me two hours or more to get done.

Using filter, we can write:
var difficult_tasks = tasks.filter(function (task) {
    return task.duration >= 120;
});
 
// Using ES6 arrow functions
var difficult_tasks = tasks.filter((task) => task.duration >= 120 );

reduce in Practice

Let's turn back to our tasks example. What If we wanted to know the total amount of time we spent working today?

With reduce, that becomes:
var total_time = tasks.reduce(function (previous, current) {
    return previous + current.duration;
}, 0);
 
// Using ES6 arrow functions
var total_time = tasks.reduce((previous, current) previous + current.duration );

In this tutorial, you've learned how map, filter, and reduce work; how to use them; and roughly how they're implemented.

For detailed explanation, visit How to Use Map, Filter, & Reduce in JavaScript

Thursday, November 23, 2017

Understanding Three Cases of Components Communication in Vue 2.0

The way components communicate, in Vue 2.0, is through props and custom events. And with Vue 2.0 release, it has actually gotten simpler. So, in this article, I’d like to show you the different cases in which components communicate, and how to handle each one properly.

Three cases of components communication:
1. From parent to direct children, no custom events required; just use props.
2. From a child to its direct parent, use $emit(eventName) in children and the directive v-on:event-name in the parent.
3. Non Parent-Child communication i.e global component communication (from any component to any component), use the global event bus. Or use Vuex for more complex cases.

1. Parent-Child communication

It's called parent-child communication because they are directly related to each other. They inevitably need to communicate to one another: the parent may need to pass data down to the child, and the child may need to inform the parent of something that happened in the child.

In Vue, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events.

Pssing data with props
Data can be passed down to child components using props. A prop is a custom attribute for passing information from parent components. A child component needs to explicitly declare the props it expects to receive using the props option:
 <template>
  <div class="message">
    {{ message }}
  </div>
 </template>

 <script>
 export default {
   name: "child",
   props: ['message'] 
 }
 </script>
Then we can pass a plain string to child component from parent like so:
 <child message="hello!"></child>

2. Child-Parent Communication

We have learned that the parent can pass data down to the child using props, but how do we communicate back to the parent when something happens? This is where Vue's custom event system comes in.

To accomplish this kind of communication, you have to do two things:
1. First, Fire an event from the child component using $emit(eventName, [data]).
2. Listen to it on the parent using the v-on:event-name directly in the template where the child component is used.

Here’s a quick example:
Let’s say you’ve built your own custom dropdown component that contains a bunch of options which you pass from the parent. When an option is selected in that dropdown, it should emit an event to its parent, so it can do its stuff.

Here’s what happens when an option is selected in Dropdown.vue:
data () {
 return {
   selectedOption: null
 }
},
methods: {
  selected () {
    // assume 'this.selectedOption' is defined in the data object
    this.$emit('option-select', this.selectedOption)
  }
}
Now in the parent component — let’s call it NavBar.vue — we’ll have something like this (note that I’m using the shorthand for v-on which is @):
 <template>
  <div class="nav-bar">
    <!-- other elements -->
    <dropdown
      :options="someOptions"
      @option-select="onOptionSelect"
    ></dropdown>
  </div>
 </template>

  <script>
  export default {
    methods: {
      onOptionSelect (option) {
      // handle it here
      }
    }
  }
 </script>

3. Non Parent-Child communication

Sometimes two components may need to communicate with one-another but they are not parent/child to each other. In other words, global component communication.

You need to handle all the communications through event hub (or some call it event bus). In its simplest definition, it's an empty Vue instance that you use globally to fire and listen for events anywhere you want in the component's tree.

As I just mentioned, this eventHub is an empty Vue instance which you’d create like this:
 //empty Vue instance 
 var eventHub = new Vue()
This needs to be globally accessible
For everything to work correctly, you need to make sure that this eventHub is accessible globally. And this depends on how your application is structured.

If you’re building a simple non-modular app, you can attach that instance to the browser’s window object.

However, for module-based applications that use bundling tools like Webpack or Browserify, you can do that by exporting that instance from a certain file and then import it wherever you need it.
 // src/shared/EventHub.js

 import Vue from 'vue'
 export default new Vue()
Now in other components, you would import it like this:
 import eventHub from 'src/shared/EventHub'
Let’s imagine that we want to pass an event from component-A to component-B. To do that, we first need to emit that event from component-A:
 import eventHub from 'src/shared/EventHub'

// …

methods: {
  doSomething () {
    eventHub.$emit('id-selected', 1)
  }
}
Now, in component-B, you would listen to it like this:
 import eventHub from 'src/shared/EventHub'

 // …

 mounted () {
 // in component B's created hook  
 eventHub.$on('id-selected', (id) => {
     // handle it however you want.
   })
 }

As simple as that! The great thing about this approach is that you're no longer concerned about the components tree structure. In other words, events can be emitted from any component and handled by any other component regardless of their relationship.

In more complex cases, you should consider to use Vuex.

Sources:
Understanding Components Communication in Vue 2.0
Vue.js Components

Wednesday, October 25, 2017

How To Add Custom Helpers on Handlebars?

You can extend handlebars with your own custom helpers. This allows you to create complex logic using handlebar’s expression system. There are 2 kinds of helpers, a function helper and a block helper. The difference is that one is meant for a single expression and the other uses a block expression.


Custom Function Helpers
Creating function helpers is relatively easy. To create one, we have to register it using the registerHelper() method. It takes the name of the helper and the helper function as arguments. Handlebars.js takes whatever is returned from the helper function and writes it out to the template, so be sure to always return a string from your custom helpers.

To write an expression helper function to output a formatted phone number, you could define the following helper:
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
  phoneNumber = phoneNumber.toString();
  return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
});
You would use the formatPhoneNumber helper in a template like this:
{{formatPhoneNumber phoneNumber}}

Custom Block Helpers
Custom block helpers are also registered with the Handlebars.registerHelper method. When a helper is used with a block, Handlebars will pass the contents of the block compiled into a function to the helper.

Here's an example block helper that compare the option with a value, letting the contents know whether a value is equal to option. If the option is an equal to a value, helper just returns the 'selected' attribute else return empty string. This helper is useful to add a 'selected' attribute conditionally on any of the option elements.
Handlebars.registerHelper("selected", function(option, value) {
 if (option === value) {
        return 'selected';
    } else {
        return '';
    }
});

You would use the selected helper in a template like this:
<select name="countries" >
 <option  value="{{code}}" {{selected code "46" }>{{country_name}}({{code}})</option>
</select>
If the country code is equal to 46 i.e Sweden, the option will be selected.

Ref: Custom Helpers – Handlebars.js Tutorial

Friday, September 29, 2017

How To Install and Configure Homestead For Laravel 5 and OSX?

Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!

Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 7.1, MySQL, PostgreSQL, Redis, Memcached, Node, and all of the other goodies you need to develop amazing Laravel applications.

STEP 1: DOWNLOADING FILES
The first step is getting the required software for Homestead. Before launching your Homestead environment, you must install VirtualBox, (VMWare, or Parallels) as well as Vagrant. I used VirtualBox and as it is free, I am pretty sure most of you guys will be using it too.

STEP 2: INSTALLING VAGRANT HOMESTEAD BOX
Once VirtualBox / VMware and Vagrant have been installed, you should add the laravel/homestead box to your Vagrant installation using the following command in your terminal. It will take a few minutes to download the box, depending on your Internet connection speed:
 vagrant box add laravel/homestead

STEP 3: INSTALLING LARAVEL HOMESTEAD
You may install Homestead by simply cloning the repository. Consider cloning the repository into a Homestead folder within your "home" directory, as the Homestead box will serve as the host to all of your Laravel projects:
 cd ~
 git clone https://github.com/laravel/homestead.git Homestead
Once you have cloned the Homestead repository, run the bash init.sh command from the Homestead directory to create the Homestead.yaml configuration file. The Homestead.yaml file will be placed in the Homestead directory:
 cd Homestead
 bash init.sh

STEP 4: CONFIGURING THE LARAVEL HOMESTEAD
Rest of the configuration is easy. The homstead.yaml is already configured for a default app.

Setting Your Provider
The provider key in your Homestead.yaml file indicates which Vagrant provider should be used: virtualbox, vmware_fusion, vmware_workstation, or parallels. You may set this to the provider you prefer. I recommend virtualbox.
  provider: virtualbox
Configuring Shared Folders/ Folder Mapping
Folder mapping means that your Guest OS and Host OS will share a common folder where you can keep your laravel files. Laravel Homestead configures a default folder in the home directory of the Host OS.The folders property of the Homestead.yaml file lists all of the folders you wish to share with your Homestead environment. As files within these folders are changed, they will be kept in sync between your local machine and the Homestead environment. You may configure as many shared folders as necessary:
folders:
    - map: ~/Code
      to: /home/vagrant/Code
Sites
Sites is a configuration array for Nginx. By default configuration, you will have a “homestead.app” pseudo-domain which will point to a folder inside the “shared folder”. Any php code inside that folder will get executed when you will go to homestead.app inside your browser. You should set it to the “public” folder of your laravel app. Again, you may add as many sites to your Homestead environment as necessary. Homestead can serve as a convenient, virtualized environment for every Laravel project you are working on:

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public

If you change the sites property after provisioning the Homestead box, you should re-run vagrant reload --provision to update the Nginx configuration on the virtual machine.
 vagrant reload --provision
Note: It’s this particular step that tends to confuse most Homestead beginners, so pay close attention to the following description. The folders object’s map attribute identifies the location in which your Laravel project will be located. The default value is ~/Code, meaning Homestead expects your project to reside in a directory named Code found in your home directory. You’re free to change this to any location you please. The folders object’s to attribute identifies the location on the virtual machine that will mirror the contents of the directory defined by the map key, thereby making the contents of your local directory available to the virtual machine.
The sites object’s map attribute defines the domain name used to access the Laravel application via the browser. Finally, the sites object’s to attribute defines the Laravel project’s root web directory, which is /public by default.


If this explanation is clear as mud, let’s clarify with an example. Begin by setting the folders object’s map attribute to any path you please, likely somewhere within the directory where you tend to manage your various software projects. For instance, mine homestead.yaml is currently set like this:
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/development/projects
      to: /home/vagrant/projects

sites:
    - map: laravel.dev
      to: /home/vagrant/projects/laravel/public

    - map: homestead.app
      to: /home/vagrant/projects/tutorials/laravel-basics/public  

databases:
    - homestead

Here is the screen dump of my Folder Structure


STEP 5: CONFIGURING THE HOST FILE
You must add the "domains" for your Nginx sites to the hosts file on your machine. The hosts file will redirect requests for your Homestead sites into your Homestead machine. On Mac and Linux, this file is located at private/etc/hosts. Open the hosts file with administrative access
  sudo nano /private/etc/hosts
The lines you add to this file will look like the following. You can add it anywhere but for ease, add it at the bottom of the file as below.
192.168.10.10   laravel.dev
192.168.10.10   homestead.app
Make sure the IP address listed is the one set in your Homestead.yaml file.

After adding above lines to the file Press cltr + o, then Enter, then cltr+x
Here is the screenshot of my host file:

STEP 6: RISE AND SHINE HOMESTEAD
Open terminal and navigate to Homestead directory and run the following vagrant up command. Vagrant will boot the virtual machine and automatically configure your shared folders and Nginx sites.
  Anup:~ anup$ cd ~/Homestead
  Anup:Homestead anup$ vagrant up
You will have your Homestead running in no time. Now go to homestead.app in your browser and be ready to get an error. Most probably “No input File Found”. It is because we don’t have laravel app’s “public” folder yet. We will install laravel in the next step.

STEP 7: INSTALL COMPOSER AND LARAVEL
Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.
Installing Composer Run this in your terminal to get the latest Composer version:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
Make composer globally accessible
After running the installer, you can run this to move composer.phar to a directory that is in your path:
mv composer.phar /usr/local/bin/composer
Now just run composer in order to run Composer instead of php composer.phar
Via Laravel Installer
After the Composer is installed successfully, download the Laravel installer using Composer:
 composer global require "laravel/installer"
Make sure to place the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system. Open .bashrc file to add required $PATH as below:
  Anup:~ anup$ nano ~/.bashrc
Add the export PATH="$PATH:$HOME/.config/composer/vendor/bin" as below:

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel's dependencies already installed.

To install Laravel, we need to go the directory we have specified on STEP 4 (i.e. sites section of homestead.yaml) as below
Anup:~ anup$ cd development/projects/tutorials/laravel-basics/
Anup:laravel-basics anup$ laravel new
It will install laravel in the laravel-basics folder. Don't forget to create .env file on root directory(i.e. remove .example extension from .env.example). Otherwise, you will get error.

My Laravel project looks like below:

STEP 8: SSH’ing INTO YOUR MACHINE
Go the the Homestead directory, run vagrant up and vagrant ssh.
 Anup:~ anup$ cd ~/Homestead
 Anup:Homestead anup$ vagrant up

After vagrant is up, then you can ssh into it as below.
 Anup:Homestead anup$ vagrant ssh
 vagrant@homestead:~$ 
Go the respective project as below and run composer install to complete the Laravel installation process.
vagrant@homestead:~$ cd projects/tutorials/laravel-basics/
vagrant@homestead:~/projects/tutorials/laravel-basics$ composer install
vagrant@homestead:~/projects/tutorials/laravel-basics$ php artisan key:generate
Your Homestead virtual machine is up and running! Open a browser and navigate to the URL http://homestead.app and you should see

You may encounter errors and problems while following the above steps but everyone do. Homestead is very easy to install and configure and after a few minutes of playing around the problems, you will be able to fix it. Let me know in the comments, if I am missing anything in the article or if you are stuck with laravel homestead.

Sources :
Laravel Installation
Install Laravel Homestead on Windows Extremely Easily
Installing and Configuring Homestead 2.0 for Laravel 5

Wednesday, September 27, 2017

How to Upgrade to PHP 7 or 7.1 on macOS?

Usually, with a fresh version of macOS Sierra, you get a PHP 5.6 installed.

Download and Install to PHP 7.0 or 7.1
You’ve got two options: brew or curl install. I am showing how to upgrade to PHP version 7.0 or 7.1 using curl method.

Open Terminal and run…
curl -s http://php-osx.liip.ch/install.sh | bash -s 7.0
or for 7.1
curl -s http://php-osx.liip.ch/install.sh | bash -s 7.1

If the output of php -v still doesn't echoes the version 7, simply type following command to update your path, it should do the magic, as stated on php-osx.liip.ch website
export PATH=/usr/local/php5/bin:$PATH

Source: How to upgrade your version of PHP to 7.0 on macOS Sierra