Good Coding Pattern and Technique in javascript

Patterns:-All languages have patterns. In javascript pattern are long-lasting and durable  or a collection a pattern that is used to solve the problem in software design .It includes function pattern, jquery pattern, design patterns, object creation pattern etc....

Some of the pattern in javscript are:

  • Module Pattern
  • Revealing Module Pattern
  • Singleton Pattern
  • Factory Pattern
  • Observer Pattern
  • Mediator Pattern
  • State Pattern 

Module Pattern:

The  ES6 and ES2015 announce an actual module pattern in javascript . It is the most common pattern in javascript. We can use module pattern to separate the file to export  module which is the customary form of a code and import them intoa new file. In ES5  module pattern breaks the code in different part and make a self-contain module which includes its private properties and its method which include the private variables and their functions.

// Basic Structure 
  (function(){
        //Declare Private Variables and functions
      return{
        //Declare Public Variables and functions

      }
  })();
//Standard Module Pattern    
const App = (function() {
        
        let text = 'My new list';
        
        const callInner = function() {
            console.log("Inner Function");
        }

        return {
           callMyFunction: function() {
               callInner();
               console.log(text);
           }
        }
    })();

// Calling
App.callMyFunction();

 

Revealing Module Pattern:

 The Revealing Module Pattern are slightly different from Module pattern. In this pattern we can define which member are public available and which are not that is private members. In this we can use a  return statement to return a object literal object  which publish method  and the properties which are available openly.

//Reveling Module Pattern
const AddedItem = (function() {
            let data = [];

            function add(item) {
                data.push(item);
                console.log('Item Added to the list....');
            }

            function get(id) {
                return data.find(item => {
                    return item.id === id;
            });
        }

        return {
            add: add,
             get: get
        }
    })();

    AddedItem.add({id: 1, ItemName: 'SUV'});
    AddedItem.add({id: 2, ItemName: 'HONDA'});
    console.log(AddedItem.get(1));
    console.log(AddedItem.get(2));

Singleton Pattern:

Singletone pattern deal with the unidentified function which can return one instance of the object at one time. It can make a private reference which means we can access nothing from the outside class. It reduces the need of global variable because of its limited namespace is a misuse  and its correlate the risk of name and the destruction. A singleton should be constant in the intense code and there should be not any problem to direct more than one of them.

//Singleton Pattern
const Singleton = (function() {
        let inst;

        function createInst() {
            const object = new Object({name:'Alfa Romeo'});
            return object;
        }

        return {
            getInst: function() {
                if(!inst){
                    inst = createInst();
                }
                return inst;
            }
        }
    })();

    const instA = Singleton.getInst();
    const instB = Singleton.getInst();

    console.log(instA === instB);

    console.log(instA);

Factory Pattern:

 Factory pattern is also called a factory method in javascript. It is used to create a interface for the object. This method is used to manage, maintain or manipulate the collection of the object that are distinct from each other at the same time they have the common properties and methods.

//Factory Pattern
    function MemberClass() {
        this.createStudent = function(name, position) {
            let member;

            if(position === 'caption') {
                member = new ClassCaption(name);
            } else if (position === 'vicecaption') {
                member = new ClassViceCaption(name);
            } else if (position === 'monitor') {
                member = new ClassMonitor(name);
            }

            member.position = position;

            member.define =  function() {
                console.log(`${this.name} (${this.position}): ${this.grade}`);
            }

            return member;
        }
    }

    const ClassCaption = function(name) {
        this.name = name;
        this.grade = '1st';
    }

    const ClassViceCaption = function(name) {
        this.name = name;
        this.grade = '2nd';
    }

    const ClassMonitor = function(name) {
        this.name = name;
        this.grade = '3rd';
    }

    const members = [];
    const class= new MemberClass();

    members.push(class.createStudent('Neel', 'caption'));
    members.push(class.createStudent('Rahul', 'vicecaption'));
    members.push(class.createStudent('Veena', 'monitor'));

    members.forEach(function(member) {
        member.define();
    });

Observer Pattern:

The observer pattern allow to subscribe or unsubscribe a certain events and function. It is used to notify the DOM of certain element to update. The observer pattern provide the facility of object-orient design and  support easy pairing and  one-to-many data binding between elements. It solve the problem of client-side scripting.

Index.html (By using Bootstrap)

<body>
 <B>Hotel List and Services</B>
            <div class="list-group">
                <ul class="list-group">
                    <li class="list-group-item" id="test1">Taj Hotel
                        <p>Complimentary arrival & departure transfers,
                            Reception with concierge assistance,
 All suites with Caldera sea view.</p>
                    </li>

                    <li class="list-group-item" id="test2">Paradies Lost
<p>Each room individually designed and furnished with Collectors Art works,
    Private and Exclusive Canopy Candlelight dinners,</p>
                    </li>
                    <li class="list-group-item" id="test3">Grand Hayat
                    <p>Porter service,
                        Free public parking,
                        Free Wi-Fi internet access throughout the hotel,
                        Manicure, Pedicure and Makeup artist services</p>
                    </li>
                    <li class="list-group-item" id="test4">Lost and Found Hotel
                    <p>Wedding planning & organizing services,
                        Doctor on call,
                        Private & semi-private sailing tours, cruises and excursions, 
                        Wine tasting tours & In house wine, food tasting.

                    </p>
                    </li>
                </ul>
            </div>
            <button class="ser-sub">Service Subscribe </button>
            <button class="pull-right unser-sub">Service Unsubscribe </button>
            <br><br>
            <button class="sub-s">Subscribe to Seconds</button>
            <button class="pull-right unsub-s"> Unsubscribe from Seconds</button>
            <br><br>
            <button class="fire">Fire</button>
  </div>

 </div>


</div>

</body>

In app.js

function EventObserver() {
        this.observers = [];
    }

    EventObserver.prototype = {
        subscribe: function(fn) {
            this.observers.push(fn);
            console.log(`You service has been   ${fn.name}`);
        },
        unsubscribe: function(fn) {
            // Filter out from the list whatever matches the callback function. If there is no match, the callback gets to stay on the list. The filter returns a new list and reassigns the list of observers.
            this.observers = this.observers.filter(function(item){
                if(item !== fn) {
                    return item;
                }
            });
            console.log(`You service has been un${fn.name}`);
        },
        fire: function() {
            this.observers.forEach(function(item) {
                item.call();
            });
        }
    }

    const click = new EventObserver();

    // Event Listeners
    document.querySelector('.ser-sub').addEventListener('click', function() {
        click.subscribe(subscribe);
    });

    document.querySelector('.unser-sub').addEventListener('click', function() {
        click.unsubscribe(subscribe);
    });

    document.querySelector('.sub-s').addEventListener('click', function() {
        click.subscribe(SubscribeforSecond);
    });

    document.querySelector('.unsub-s').addEventListener('click', function() {
        click.unsubscribe(SubscribeforSecond);
    });

    document.querySelector('.fire').addEventListener('click', function() {
        click.fire();
    });

    // Click Handler
    const subscribe = function() {
        console.log(`Current Milliseconds: ${new Date().getMilliseconds()}`);
    }

    const SubscribeforSecond = function() {
        console.log(`Current Seconds: ${new Date().getSeconds()}`);
    }

Mediator Pattern:

 A mediator pattern is a behavioral design pattern that allows us to display a collective interface through which the different parts of a system may communicate with each other. It is helpful in the development of the complicated forms and events like chat messengers, games etc where need to encapsulate data and actions.

var User = function(name) {
    this.name = name;
    this.chatroom = null;
};
 
User.prototype = {
    send: function(message, to) {
        this.chatroom.send(message, this, to);
    },
    receive: function(message, from) {
        console.log(from.name + " to " + this.name + ": " + message);
    }
};
 
var UserGroup = function() {
    var users = {};
 
    return {
        register: function(user) {
            users[user.name] = user;
            user.chatroom = this;
        },
 
        send: function(message, from, to) {
            if (to) {                      // single message
                to.receive(message, from);    
            } else {                       // broadcast message
                for (key in users) {   
                    if (users[key] !== from) {
                        users[key].receive(message, from);
                    }
                }
            }
        }
    };
};
 
function run() {
    var user_a = new User("User A");
    var user_b = new User("User B");
    var user_c = new User("User C");
    var user_d = new User("User D");
 
    var group = new UserGroup();
    group.register(user_a);
    group.register(user_b);
    group.register(user_c);
    group.register(user_d);
 
    user_a.send("Broadcast Message By A");
    user_b.send("Broadcast Message By B");
    user_c.send("Single Message C to A", user_a);
    user_d.send("Broadcast Message By D");
}

run();

Output:

User A to User B: Broadcast Message By A
User A to User C: Broadcast Message By A
User A to User D: Broadcast Message By A
User B to User A: Broadcast Message By B
User B to User C: Broadcast Message By B
User B to User D: Broadcast Message By B
User C to User A: Single Message C to A
User D to User A: Broadcast Message By D
User D to User B: Broadcast Message By D
User D to User C: Broadcast Message By D

State Pattern:

In javascript Frameworks like React, Angular usages MVC approch. MVC approch usages the state pattern to mange the states of values in javascipt. Lets take a simple example of this pattern.

var VolumeLevels = function () {
    var count = 0;
    var currentLevel = new Medium(this);
 
    this.change = function (state) {
        if (count++ >= 10) return;
        currentLevel = state;
        currentLevel.go();
    };
 
    this.init = function () {
        currentLevel.go();
    };
}
 
var High = function (volume) {
    this.volume = volume;
 
    this.go = function () {
        console.log("Volume is High");
        volume.change(new Low(volume));
    }
};
 
var Medium = function (volume) {
    this.volume = volume;
 
    this.go = function () {
        console.log("Volume is Medium");
        volume.change(new High(volume));
    }
};
 
var Low = function (volume) {
    this.volume = volume;
 
    this.go = function () {
        console.log("Volume is Low");
        volume.change(new Medium(volume));
    }
};
 
function run() {
    var volume = new VolumeLevels();
    volume.init();
}

run();

Output:

Volume is Medium
Volume is High
Volume is Low
Volume is Medium
Volume is High
Volume is Low
Volume is Medium
Volume is High
Volume is Low
Volume is Medium
Volume is High


Keywords: