MyArchiBook

Posts Tagged ‘es6

ES6 Generator functions – A beauty !

leave a comment »

ES6 Generator* function is one of the unique features which helps maintain a flat & clean code.

Example:
Let’s consider a simple example of getting pizza.

Promise based implementation:

generator-promise-based

Generator fn based implementation:

generator-fn

Explanation:

  • Generator fn differentiates itself from other functions by *
    ie., function* pizzaGenerator() or function *pizzaGenerator()
  • runGenerator() can be considered as a util that executes generator function.
  • generator() returns iterator object which exposes next() that helps move to targets in sequence.
  • yield in generator function*() is synonymous to pause. It helps pause the next line execution until the current execution result is obtained (be it function call or promise)

It’s usage has made my code very straight-forward, flat & clean.

References:

Written by thangaveluaishwarya

May 29, 2017 at 12:27 AM

ES6 modules & classes with Webpack: quick setup & usage

with one comment

For setting up and using ES6 Modules with webpack perform the following steps:

  1. quicky setup js-sdk library using webpack
  2. Install babel-loader and its dependencies.
    npm install babel-loader babel-core babel-preset-env --save-dev
    Here babel-loader is the main package for invoking Babel transpilation. It requires babel-core for apis. babel-presets has the plugin for module-loading.
  3. Configure webpack.config.js
  4. vi index.js

    //Class definition
    export default class Imax {
      get movies() {
        return ['Logan', 'Beauty and the Beast'];
      }
      bookMovie(name) {
        return `Thank you for booking with Imax. Booking ID is ASDFFG|${name}`;
      }
    }
    
    module.exports = new Imax();
  5. webpack // build library
  6. webpack-dev-server  // host library. (hosted locally here)
  7. Client side:
    $.getScript('//localhost:8080/assets/imax.js').then(() => {
        let selectedMovie = Imax.movie[0];
        console.log('Movie list: ', Imax.bookMovie(selectedMovie));
     });
    
  8. O/P:
    Thank you for booking with Imax. Booking ID is ASDFFG|Logan

References:

Written by thangaveluaishwarya

March 24, 2017 at 11:17 AM