Factory function

What is factory function? And before this question, whatever it is, why I am going to use it. Hah!

Let us consider this example

I am creating two persons objects like

var johnDoe = {
    firstName : ”John”,
    lastName : ”Doe”,
    sayHi  : function(){
        return “Hi there”;
    }
};

var janeDoe = {
    firstName : ”Jane”,
    lastName : ”Doe”,
    sayHi  : function(){
        return “Hi there”;
    }
}

We created two objects so what if I want to create 10 more person object. Should I write these lines 10 more time? Opps! Sorry!

This is the situation where we are going to use factory function. In Javascript there are two function by which we can create object, one is constructor function and another is factory function.

[cc lang="javascript"]
var createPerson = function(fName , lName){
    return {
        firstName : fName,
        lastName : lName,
        sayHi : function(){
            return “Hi there”;
        }
    };
};

var johnDoe = createPerson(“John”,”Doe”);

var janeDoe = createPerson(“Jane”,”Doe”);
[/cc]

If we want to create multiple objects with same interface, this is the better way. Remember, Interface is a signature. Hope you understood what I am trying to say.

Iterating complex data structure

Let say we have an array of authors


const myFavouriteAuthors = [
  'Neal Stephenson',
  'Arthur Clarke',
  'Isaac Asimov', 
  'Robert Heinlein'
];

we can iterate all authors using any loop or for of here, but if we modify the data structure in below format,


const myFavouriteAuthors = {
  allAuthors: {
    fiction: [
      'Agatha Christie', 
      'J. K. Rowling',
      'Dr. Seuss'
    ],
    scienceFiction: [
      'Neal Stephenson',
      'Arthur Clarke',
      'Isaac Asimov', 
      'Robert Heinlein'
    ],
    fantasy: [
      'J. R. R. Tolkien',
      'J. K. Rowling',
      'Terry Pratchett'
    ],
  }
}

then you cannot iterate all authors using for loop or any other loop with ease. So we can write our own method


const myFavouriteAuthors = {
  allAuthors: {
    ...
  },
  getAllAuthors() {
      const authors = [];

      for (const author of this.allAuthors.fiction) {
          authors.push(author);
      }

      for (const author of this.allAuthros.scienceFiction) {
          authors.push(author);
      }

      for (const author of this.allAuthors.fantasy) {
          authors.push(author);
      }

      return authors;
  }
}

The problem with this approrach is we need to be aware of the method called getAllAuthors and if our data sctructure has one more genre then we need to modify the getAllAuthors function as well. This is not cool.

So, what’s the other approach is make our data structure iterable. Can we do that. Yes we can!!

An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol.iterator. That method is a factory for iterators. That is, it will create iterators.

const myFavouriteAuthors = {
  allAuthors: {
    fiction: [
      'Agatha Christie', 
      'J. K. Rowling',
      'Dr. Seuss'
    ],
    scienceFiction: [
      'Neal Stephenson',
      'Arthur Clarke',
      'Isaac Asimov', 
      'Robert Heinlein'
    ],
    fantasy: [
      'J. R. R. Tolkien',
      'J. K. Rowling',
      'Terry Pratchett'
    ],
  },
  [Symbol.iterator]() {
    // Get all the authors in an array
    const genres = Object.values(this.allAuthors);

    // Store the current genre and author index
    let currentAuthorIndex = 0;
    let currentGenreIndex = 0;

    return {
      // Implementation of next()
      next() {
        // authors according to current genre index
        const authors = genres[currentGenreIndex];

        // doNotHaveMoreAuthors is true when the authors array is exhausted.
        // That is, all items are consumed.
        const doNothaveMoreAuthors = !(currentAuthorIndex < authors.length);
        if (doNothaveMoreAuthors) {
          // When that happens, we move the genre index to the next genre
          currentGenreIndex++;
          // and reset the author index to 0 again to get new set of authors
          currentAuthorIndex = 0;
        }

        // if all genres are over, then we need tell the iterator that we 
        // can not give more values.
        const doNotHaveMoreGenres = !(currentGenreIndex < genres.length);
        if (doNotHaveMoreGenres) {
          // Hence, we return done as true.
          return {
            value: undefined,
            done: true
          };
        }

        // if everything is correct, return the author from the 
        // current genre and incerement the currentAuthorindex
        // so next time, the next author can be returned.
        return {
          value: genres[currentGenreIndex][currentAuthorIndex++],
          done: false
        }
      }
    };
  }
};

for (const author of myFavouriteAuthors) {
  console.log(author);
}

console.log(...myFavouriteAuthors)

Implement synchronous run for asynchronous tasks

This is a programming problem of running two asynchronous function in synchronous manner. We have few async tasks t1, t2 and t3.

var t1 = function(arg){
  console.log('Task 1 start');
  setTimeout(function(){
    console.log('Task 1 end');
    arg();
  }, 500);
}


var t2 = function(arg){
  console.log('Task 2 start');
  setTimeout(function(){
    console.log('Task 2 end');
    arg();
  }, 100);
}

var t3 = function(arg){
  console.log('Task 3 start');
  setTimeout(function(){
    console.log('Task 3 end');
    arg();
  }, 200);
}

We want to implement a runSync method which takes array of these tasks, but run them synchronously.

Lets create a task array, tasks = [t2, t3, t1], and t3 should run only when t2 is finished and then run t1.

var runSync = function(tasks){
  var i = 0;

  function run(){
    if(i < tasks.length){
      tasks[i](run);
      i++;
    }

  }

  run();
}

runSync([t3,t1,t2]);

Is jQuery really dead

Not sure. Before being declared it is dead. We need to check its pulse. We need to check why it came into existence.

The fundamental concept of jQuery is its nature of hiding complexity. I bet many of us don’t remember the exact syntax of doing an ajax call with vanilla javascript, but sure you can recall doing an ajax call using jQuery. Yeah!. You got it. jQuery is built on a design pattern also known as Facade. Hiding complexity is the core idea of facade pattern.

Let’s recall the problem jQuery solved for us and its alternative solution. First and foremost is jQuery selectors. We can use the power of CSS selectors with jQuery. Introduction of querySelctor and querySelectorAll has already eliminated the use of jQuery selectors.

Ajax call by jQuery. jQuery came up a long way from success and failure callback syntax to syntax returning promises for ajax call but now developers are more towards reactive programming so using RxJS.

Who can forget the contribution jQuery made in the field of animation? How to move stuff here and there and at what rate. CSS3 animation APIs has already fixed these things with more efficiency (CSS uses GPU not CPU).

jQuery never solved the problem of dependency injection. We were always dependent on some other libraries like RequireJS, Steal etc for this feature.

Although jQuery provided a quick solution for design, fewer lines of codes, millions of plugin, but has not provided any MVC(Model-View-Controller) structure to applications. Whereas this is the era of frameworks, where framework takes care of solving problems for us. Writing how to do is no more the pattern(imperative programming). ReactJS provides the way where we describe(declarative approach) what we want, and frameworks take care of how to do it.

In the end, you can find traces of jQuery in almost every website, but they are legacy. We should salute jQuery for its contribution before it is gone. It will live in memories of many source code with their hallmark sign of $.

Remember every $ is not jQuery. Link for this article in medium

Fear of Frontend Developer

I slept for a night just for a few hours and when I woke up there is a new JavaScript framework born. The irony is there are many new framework and library coming out who I don’t know about. I don’t know how much I need to upgrade my self. I hope all the web developer interview should focus on basics. But this is not the perfect world. Some company wants a angular guy, who know how to code in angular, that’s it.

I am a simple web developer in India, by far I have not contributed enough to any open source, not a consistent member of any community. Looks like there is a lot to learn. But what would you do, if your syllabus is increasing day by day. That’s the fear I am talking about. What I did til now is follow some good people on twitter, completed my Front End Certificate in FreeCodeCamp(which I am proud of, almost 10000 hrs of coding), created a blog where I put my day to day learning(jforjs.com), few videos in Youtube. I know, I know. This is not enough.

One thing I like about this fearful life is that I am on the continuous learning path. I started loving JavaScript. I got respect for other programming languages too. I came to know, every warrior in this battle has some skills, which I can learn from them. Some of those warriors are React Ninjas, some are JS Gurus and some are new bees with amazing learning skills. Isn’t this amazing. We have new level from Functional Programming to Dyanamic Programming, IOT to Machine Learning, and hell I know what is there more to learn.

I am glad that I choose this path, and its great to be fearful. It has more pros than cons. Find this article in medium

Patterns with Async call : Beautiful Javascript

Asynchornous call is very famous for its callback hell

getData(a => {
    getMoreData(a, b => {
        getMoreData(b, c => {
            getMoreData(c, d => {
                getMoreData(d, e => {
                    console.log(e);
                });
            });
        });
    });
});

Promise Hell

getData()
.then(a => getMoreData(a))
.then(b => getMoreData(b))
.then(c => getMoreData(c))
.then(d => getMoreData(d))
.then(e => console.log(e));

Its’ not over yet

getData()
.then(getMoreData)
.then(getMoreData)
.then(getMoreData)
.then(getMoreData)
.then(console.log);

Looks synchronous with async-await

(async () => {
    const a = await getData();
    const b = await getMoreData(a);
    const c = await getMoreData(b);
    const d = await getMoreData(c);
    const e = await getMoreData(d);
    console.log(e);
})

Implementing Throttle Function

What is a throttle function. “throttle” function returns a function which will run only once with in the time specified. This is very useful when we wish to perform some operation only once even when the function is called multiple times.
For more details, please follow the link.

In this article we are discussing how can we implement our own throttle method. The definition of our function should be

function throttle(fn, timeInMilliseconds){
    return function(){
      ...
    }
}

So. let’s create a boolean variable which will in closure here, and change it only when the function is called or after certain time limit.

function throttle(fn, timeInMiliseconds){
  var t = true;

  return function(){
    if(t){
      fn();
      t = false;

      setTimeout(function(){
        t = true;
      },timeInMiliseconds);
    }
  }
}

Testing our throttle function

function hello(){
  console.log('hello');
}

//This returns a function which will only run once in 5 seconds.
var throttled = throttle(hello, 5000);

throttled(); //print hello
throttled(); //5 second isn't over yet

setTimeout(function(){
  throttled();
}, 2000); // 5 second isn't over yet

setTimeout(function(){
  throttled();
}, 6000); //print hello

Web Scraping through YQL and nodejs

Web scraping (web harvesting or web data extraction) is a computer software technique of extracting information from websites.

I used a node module call YQL(Yahoo Query Language) to achieve it. You may have many other ways to do the same.

  1. npm install yql (this will download yql module for your node project)

  2. app.js file.

var http = require("http");
var YQL = require("yql");
var port = 3000;
var serverUrl = "localhost";
var word = {
    "english": "",
    "hindi": ""
};


new YQL.exec('select * from data.html.cssselect where url="http://shabdkosh.com/" and css="p.engwotd"', function(response) {
    word.english = response.query.results.results.p.content;
});

new YQL.exec('select * from data.html.cssselect where url="http://shabdkosh.com/" and css=".indwotd"', function(response) {
    word.hindi = response.query.results.results.p.content;
});

var server = http.createServer(function(req, res) {
    console.log(word.english, word.hindi);
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(word));
});

console.log("Listening at " + serverUrl + ":" + port);
server.listen(port, serverUrl);
  1. node app.js

  2. hit your url : http://localhost:3000/

SASS compilation with grunt

When SASS file is compiled, you get .CSS file. I am not going to explain the syntax of SASS, instead of that I will explain how it is setup with grunt so that you can compile the SASS file easily.

Prerequisite for SASS

  1. Node js installed
  2. grunt installed
Now go to the specific folder where you want to setup your web project and install grunt-contrib-sass package. There are many ways to do that. Simplest one is running command in your terminal or command prompt.
npm install grunt-contrib-sass
This will download grunt-contrib-sass package in your node_modules folder. Another way of install this package is by including dependencies in package.json file.

Create a simple html file where you can apply your generated stylesheet(.css).

Now create a sample .sass file called style.sass

$primary-color: #FCF

body
  color: $primary-color

Once you done with that you need to create grunt file named GruntFile.js and write the below code in that file.

module.exports = function(grunt) {

grunt.initConfig({
  sass: {                              // Task
    dist: {                            // Target
      options: {                       // Target options
        style: 'expanded'
      },
      files: {                         // Dictionary of files
        'style.css': 'style.sass'       // 'destination': 'source'
      }
    }
  }
});

grunt.loadNpmTasks('grunt-contrib-sass');

grunt.registerTask('default', ['sass']);

};

now run the below command in your terminal

grunt

This command will compile your style.sass file into style.css. You can see the directory for newly created file, which will look like

body {
  color: #ffccff;
}

Open your index.html file which you have created earlier by following this tutorial.