Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, 29 December 2023

Understanding Rest & Spread operator in Javascript

 Background

In JavaScript, we tend to use rest & spread operators to keep code simple and easy to read. Both use three dots "..." but the use cases are different. In this post, we will see what these operations are and how to use them.


Before we proceed to looking into individual aspects just remember rest is for collecting elements and spread is for spreading elements. 

Rest operator

Let's try to see the rest operators 1st. The rest operator is used to collect the remaining elements in an array. The rest syntax works in both function arguments and arrays. Let's look at an example below



As you can see whatever number of arguments you pass to add function is going to capture 1st two in a & b respectively (in this case 1 & 2) and the remaining ones (values - [3, 4]) will be captured in an argument called rest which is an array.

The rest operator is also used for destructuring arrays like below

Spread operator

The Spread operator introduced in ES6 as the name suggests is used to spread the elements.
For eg, in the above code, you can see how "123" was split automatically into 1,2 & 3 by the spread operator.

We can also use this operator to easily create copies of arrays and objects. For eg.,



 NOTE: Spread operator helps maintain immutability requirements. This is helpful when you need data that should not mutate (Eg. Redux state).

As I mentioned before rest and spread operators are used commonly in javascript and we will see more usages and examples in upcoming posts.

Related Links




Closures in Javascript

 Background

In one of the earlier posts, we saw how to use Javascript (JS) closures to hide variables from the console with a counter-example. In this post, I will explain JS closures in more detail.

Closures in Javascript

Quoting closures from MDN web docs:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

It's important to note that it is not just a function but a combination of function + referenced to its lexical environment.  

Let's take a simple example:

(() => {
    var name = "Aniket";
    const displayName = () => {
        console.log(name);
    }
    displayName();
})()

The (()=>{})() is a self-executing function. Inside it, you can see an anonymous function defined using the arrow operator. Inside this function, we have defined a variable called name and again an anonymous function called displayName which prints the name variable in the console. 

What is interesting to note here is that even though the variable name is local to the outermost anonymous function we can still access it inside the displayName method, this is possible due to closures. When we created an anonymous function & assigned it to the displayName const variable it actually created a closure that comprised of the function itself + the reference to the lexical environment which includes the name variable defined in the outer scope.

NOTE: Nested functions have access to variables declared in their outer scope.

Understanding scopes

In the above examples, the variable name was defined in a function and had functional scope. It was accessible in that function + the methods nested inside it. It will not be accessible in the global scope. 

Before ES6 there were just two scopes, function scope and global scope. variables defined inside a function had function scope where whereas those defined outside had global scopes. This came with its own challenges as now if you define variables inside if else block braces then it creates a global scope because blocks with curly braces do not create scopes.

Eg. see below

Here check variable even though was defined inside the if block has become a global scoped variable (Unlike other languages like Java where it would have created a local scoped variable). 

To handle this ES6 introduced two new declarations
  • let - defines a variable local to the scope
  • const - defines a constant variable again local to the scope.
See below for example:





NOTE: Closure gives the function access to its outer function but the outer function can also be a nested function inside another outer function. In such cases, the innermost function will have access to all the outer nested functions via the closure chain. See eg below



Interesting examples

Now let's see some interesting examples before we wind this up.

See the below examples & predict the output

const myName = ["Aniket", "Abhijit", "Awantika"];
for(var i; i<myName.length;i++)
{
	setTimeout(function(){
    	console.log('Name: ' + myName[i] + 'at index:' + i);
    },3000)
}

The output is


It prints undefined as Name & index as 3 all the three times the loop executes. Let's try to understand why this happened: When we pass a custom function inside setTimeout it creates a closure of the function bundled with the captured environment from the out functions scope. Three closures are created by the loop but each shares the same lexical environment which has the variable "i" with changing values. This is because the "i" variable is defined as var and has a global scope. The value of "i" in the passed function is determined when it is actually executed after the timeout completes (when it comes from the event loop). Since the loop has already been completed by the time these closures from the event loop are executed "i" points to 3 and there is no such index in that array as the size is 3 and the index range from 0 to 2. Hence it prints "i" as 3 and the name as "undefined" three times - one for each closure created in the loop.

You can fix this by using a wrapper function to be passed inside setTimeout API argument which will create its own closure with the actual local value of "i" and pass it to the event table instead of just the original closure which is pointing to global scoped "I". Eg see below where I have given two ways one using function keyword and one using anonymous function



Or you could simply change var to let in the for loop which will create a block-scoped variable instead of a global scope and changes will still work fine.



Related Links

Saturday, 16 May 2020

How to add code Syntax highlighting to your blogger blog?

Background

If you own a technical blog or a website you generally need to add code to illustrate your examples. In such cases highlighting the code becomes essential. You would have seen the code syntax highlighting in this blog itself.




In this post, I will show you how you can achieve this.


How to add code Syntax highlighting to your blogger blog?

For code syntax highlighting we will use SyntaxHighlighter. I will specifically tell you how to add this to your blogger blog.


  • Open your blogger blog dashboard
  • Go to Theme
  • Click on 3 dots beside "My theme" and click on  "Edit HTML"








  • In the panel which opens and shows some HTML code search and go to the line with </head> tag. This is where your head tag ends. We need to add some include CSS and js files here along with some custom javascript.
  • Inside the head tag (Just before </head> add following code)

    <!-- Syntax Highlighter START -->
    <link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css"></link>
    <link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css"></link>
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript">
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
    <script language='javascript' type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
    </script>
    
    

  • Once done save the file and reload blog.


  • Now if you want any highlighting you can use the corresponding class in <pre> tag. Eg for Java you can do
    <pre class="brush:java">This will be highlighted</pre>
  • Instead of Java you can have other languages as well. Choices are: cpp, c, c++, c#, c-sharp, csharp, css, delphi, pascal, java, js, jscript, javascript, php, py, python, rb, ruby, rails, ror, sql, vb, vb.net, xml, html, xhtml, xslt. You can see the latest list of supported languages.
  • You can only add js files for brushes you need (See optimization below)

Optimizations

This is the good part! We would not call ourselves programmers if we did not have an optimization part :)


  • You can see above there are a bunch of js files added in the head tag. You might not need all and each page load with load these external JS code which can slow loading if your blog. So Add only those JS files which you need. In fact, if you see the screenshot above I have used just the Java brush JS. I just use the same for all types of codes.


  • If you do not want the code highlighting to work for your homepage (Just for the the posts you write), you can add all above code inside the following tags:

    <b:if cond='data:blog.pageType == "item"'>
    </b:if>
    
    
  • Lastly, you would have also noticed the link base path for JS and CSS files are different in my code that what I originally provided. That's because I have used the CDN path(https://cdnjs.com/libraries/SyntaxHighlighter). This is done primarily for 2 things:
    • First, it allows highlighting to work even on https. By default with the above code loading your blog site with https protocol will not show highlighting. That's because your include scripts are HTTP and not supported for https.
    • Secondly, if the HTTP links are down you are screwed. CDN caches the scripts and cs files. So you can always rely on it (rely is is a strong word but it's better than those HTTP links :) )

Configuration


  • Another thing you might have noticed is the change of theme file I have used. The original set of code I proposed uses a default theme shThemeDefault.css but I have changed this to use shThemeEmacs.css. You can use whichever theme you like - Just include the corresponding theme CSS file (and remove the default one).  Some of the available themes are: shThemeRDark, shThemeMidnight, shThemeMDUltra, shThemeFadeToGrey, shThemeEmacs, shThemeEclipse, shThemeDjango, shThemeDefault, shCoreRDark, shCoreMidnight, shCoreMDUltra, shCoreFadeToGrey, shCoreEmacs, shCoreEclipse, shCoreDjango, shCoreDefault



  • I already mentioned you should only include and use the JS files corresponding to language brushed you intent to use. This will reduce your page load time. You can also use the "b:if" tag I mentioned above so that these scripts load for your blog posts.

You can already see this blog using all of these customizations. Feel free to comment if you need any help. Thanks.

Related Links



Sunday, 24 February 2019

How to write Mocha and Chai unit tests for your Node.js app?

Background

Testing is an important part of the development lifecycle. Testing can be of many types - unit testing, integration testing, manual testing, QA automation testing. In this tutorial, I am going to show how you can write unit tests for your Node.js application using Mocha and Chai frameworks.  

Mocha is a javascript test framework and Chai is an assertion library. 

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases.

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.


Sample Node.js App

Let's start by writing a simple Node.js app that does addition and subtraction and then we will see how we can write tests for it using Mocha and Chai.

Create a directory called mochatest and navigate to that directory using the following commands -
  • mkdir mochatest
  • cd mochatest
Now initialize it as npm module using -
  • npm init -y



You can see the package.json content initialized with default values. Now let's install our dependencies - mocha, and chai. Execute following command -

  • npm install mocha chai --save-dev
Notice we are saving it as dev dependency and not actual dependency since we need this for testing only.




This should create a node_module directory in your current mochatest directory and install your dependencies there. You can also see dependencies added in package.json.



Now let's create our main app. You can see in the package.json above the main file is called index.js. At this point, I would request you to open your application in your favorite IDE. I will be using visual studio code for this. 

Now create a file called index.js in mochatest folder. and add the following content to it


var addition = function(a,b) {
    return a + b;
}
var subtraction = function(a,b) {
    return a - b;
}


module.exports = {
    add: addition,
    subtract: subtraction
}

This essentially exports 2 functions -
  • add 
  • subtract
that does exactly what the name says - adds and subtracts two numbers. Now let's see how we can write mocha tests for these.


How to write Mocha and Chai unit tests for your Node.js app?

In the mochatest folder create a folder called test. We will have test files in this folder. It is recommended to have same file structure as your actual app. Since we just have a single file called index.js in our app, create a file called indexTest.js in your test folder and add following content to it.


const assert = require('chai').assert;
const index = require("../index");

describe("Index Tests", function(){

    describe("Addition", function(){
        it("Addition functionality test", function() {
            let result = index.add(4,5);
            assert.equal(result,9);
        });
        it("Addition return type test", function() {
            let result = index.add(4,5);
            assert.typeOf(result,'number');
        });
    });

    describe("Subtraction", function(){
        it("Subtraction functionality test", function() {
            let result = index.subtract(5,4);
            assert.equal(result,1);
        });
        it("Subtraction return type test", function() {
            let result = index.subtract(5,4);
            assert.typeOf(result,'number');
        });
    });   

});

Let me explain this before we go and test this out. Like I mentioned before chai is an assertion library, so we get a reference to it. Then you get a reference to the actual app file - index.js. Remember it exports two functions -

  • add
  • subtract
Then we have "describe" keyword. Each describe is a logical grouping of tests and you can cascade them further. For example in the above case, we start a grouping on the basis if file meaning these group has tests for file index.js. Inside it, we have cascaded describe for each method - add and subtract. Each "describe" takes 2 arguments - 1st one is the string that defines what the grouping is for and the 2nd one is the function that has the logic of what that group does. It could have other subgroups as you see above.

Inside describe you can define actual tests inside "it" method. This method also takes 2 arguments - 1st one says what the test does and the 2nd one is a function that gets executed to test it. Inside it we use the assert reference we got from chai module. In this case, we have used
  • equal
  • typeof
You can see others in https://www.chaijs.com/guide/styles/



NOTE: By default, mocha looks for the glob "./test/*.js", so you may want to put your test methods in test/ folder.

Now let's run it. Use the following command -


  • mocha




And you can see the results. You can change the logic in index.js to see that tests fail. For example, lets change add method to return a-b instead of a+b and rerun this test. You will see the following output -


Finally, let's plug this in the npm system. package.json already has test script as follows -

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },


change this to


  "scripts": {
    "test": "mocha"
  },


and you can simply run following command to execute tests -

  • npm run test



Let me know if you have any questions. Thanks.


Related Links



Tuesday, 16 October 2018

Lerna Tutorial - Managing Monorepos with Lerna

Background

Lerna is a tool that allows you to maintain multiple npm packages within one repository. There are multiple benefits of using such an approach - one repo, multiple packages. This paradigm is called monorepo (mono - single, repo - repository). You can read more about monorepo -
To summarise pros are -
  • Single lint, build, test and release process.
  • Easy to coordinate changes across modules. 
  • A single place to report issues.
  • Easier to set up a development environment.
  • Tests across modules are run together which finds bugs that touch multiple modules easier.
Now that you understand what a monorepo is, let's come back to Lerna. Lerna is a tool that helps you manage your monorepos. In this post, I am going to show you a complete tutorial of how you can use lerna to manage a custom multi package repo that we will create.





Lerna Tutorial -  Managing Monorepos with Lerna

First of all, you need to install lerna. Lerna is a CLI. To install it you need to execute following command -
  • npm install --global lerna
This should install lerna in your local machine globally. You can run the following command to check the version of lerna installed -
  • lerna -v
 For me, it's 3.4.1 at the time of writing this post. Now let's create a directory for our lerna demo project.  Let's call it lerna-demo. You can create it with the following command -
  • mkdir lerna-demo 
Now navigate inside this directory
  • cd lerna-demo
Now execute following command -
  • lerna init
This should create a basic structure of monorepo. Take a look at below picture to understand it's structure.


 It does following things -
  1. Creates packages folder. All packages go under this.
  2. Creates package.json at the root. This defines global dependencies. It has the dependency on lerna by default.
  3. Creates lerna.json at the root. This identifies lerna repo root.
 Now let's go to packages folder and start creating our packages. We will then see how we can link them and use. So navigate to packages directory.
  • cd packages

Package - AdditionModule

Let's create a package that takes care of addition. Let's call it AdditionModule. Create a directory for this inside packages folder and execute following commands -
  • mkdir AdditionModule 
  • cd AdditionModule 
  • npm init -y
This should create a file called package.json inside AdditionModule directory. Now in the same folder create a file called index.js in the same folder and add following content to it -

module.exports.add = function(x,y){
    return x + y;
}


Save the file. This basically exposes add method to any other package that would have a dependency on this. Your 1st package is done. Let's create one more package for subtraction.

Package - SubtractionModule

 Run similar commands inside packages folder -

  • mkdir SubtractionModule
  • cd SubtractionModule
  • npm init -y
 Now in SubtractionModule folder create a file called index.js and add following code to it -

module.exports.subtract = function(x,y){
    return x - y;
}


Save the file. This basically exposes subtract method to any other package that would have a dependency on this. Now let's create a package that would have a dependency on  AdditionModule and SubtractionModule and can use add and subtract functions.

Package - Calc

Our final package - let's call it Calc would have a dependency on  AdditionModule and SubtractionModule packages. So let's create the package 1st -

  • mkdir Calc
  • cd Calc
  • npm init -y
Now create a file called index.js and add following content to it -

var add = require('AdditionModule');
var subtract = require('SubtractionModule');

var sum = add.add(2,3);
var diff = subtract.subtract(3,2);

console.log("Sum: " + sum + " Diff: " + diff);

Save the file. Now open package.json to add our dependencies. Edit package.json to add following content to it -

  "dependencies": {
      "AdditionModule": "1.0.0",
      "SubtractionModule": "1.0.0"
   },


So your entire package.json looks like -

{
  "name": "Calc",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
      "AdditionModule": "1.0.0",
      "SubtractionModule": "1.0.0"
   },
}

Now you are all set up. Your directory structure should look like below -



Now it's time to use lerna to link packages. Go to lerna-demo directory and execute the following command -
  • lerna bootstrap
 This should do all linking for you. It would create node_modules directory in Calc package and add symlinks to AdditionModule and SubtractionModule. Your directory structure would now look like -


Now you can simply run calc index.js as follows -

  • node packages/Calc/index.js
And you should get expected output -




The important thing was the linking part that lerna does for you so that you do not have to worry about it.


For complete details on all available commands see - https://github.com/lerna/lerna

Related Links




Friday, 2 February 2018

Simulating environment variables in NodeJs using dotenv package

Background

When you write code there are certain variables that may differ as per the environments like dev, qa prod etc. This might have sensitive data as API keys, passwords etc. You would definitely do not want to put it in your code directly since this will be added to some code repository like git and others may have access to the same. 

General practice that is followed is to use environment variables that can be defined at the environment level and can be read and used in the code. For eg. consider Elastic beanstalk or a Lambda in AWS world. You would define environment variables for the environment and use that in code. If it's your our physical box you might define the environment variables at the OS level or maybe at tomcat level if you are using tomcat as the container. Environment variables work fine in all such cases. 

But how would you do the same in local. In this post I will show how we can simulate environment variables in a NodeJs process with a package called dotenv.


This post expects you to know basics of NodeJs and have NodeJs and npm (Node package manager) installed on your machine. If you have not done that then please refer my earlier post -

Simulating environment variables in NodeJs using dotenv package

First you need to install dotenv package using npm. To do so go to the directory where you would have your NodeJs file and execute following command -
  • npm install dotenv
If you get some warning you can ignore it for now. You should see a directory called node_modules getting created in the same directory where you executed this command. This folder will have the package dotenv that we just installed.


Now that we have package installed let's see how we can simulate an environment variable. For this simply create a file name .env in the same directory and add the environment variable you expect to read in code in it. For this demo I will use 3 environment variables -
  • ENVIRONMENT=local
  • USERNAME=athakur
  • PASSWORD=athakur
Now create NodeJS file in the same directory. Let's call it test.js. The directory structure is as follows -



Add following content in test.js -

'use strict';
const dotenv = require('dotenv');
dotenv.config();

const env = process.env.ENVIRONMENT
const username = process.env.USERNAME
const password = process.env.PASSWORD

console.log("Env : " + env);
console.log("Username : " + username);
console.log("Password : " + password);

Save the file and execute it as -
  • node test.js
You should see following output on the screen -

Env : local
Username : athakur
Password : athakur


And that's it. You can add any number of environment variables in the ".env" file and read it in your node js code as process.env.variable_name.

NOTE :  .env file would be hidden in Ubuntu since Ubuntu hides all files that start with a dot (.). You can just press Ctrl + H to view hidden files or do a "ls -la" in console. More details -






To read more about this package  you can read -


Related Links


Saturday, 11 November 2017

Understanding Promises in javascript

Background

I am really new to nodejs and javascript for that matter. I have used these in past but mainly to manipulate DOM elements, post forms , handle event etc. We saw in last post on node.js working how node.js works on single threaded, non-blocking and asynchronous programming model.
This is achieved mainly using events. So lets say you want to read a file on the file system. You make a call to access this file and essentially provide a callback function which will be invoked on successful completion of file access and meanwhile program can carry on with it's next set of function.

Now sometime we do need to synchronise tasks. For example lets say we want to complete reading files json content which is required to make a network call. One possible way is to do the network call in the callback function of the file access function so that when we get a callback on file access completion we read the file and then make a network call. 

This sounds simple enough for a single function to be synchronised. Try to imagine multiple functions that need to be synchronised.   It can be a nightmare coding that - writing new function in each functions callback (cascading it). 

This is where promises come into picture.



Understanding Promises in javascript


It is literally what it means - a promise. It is an object that may produce a result in the future. Think of it like a Future object in Java (I come from a Java background, hence the reference. Ignore if you are not aware) -

 A promise of a function can be in either one of the following state -
  1. Fulfilled : Asynchronous operation corresponding to this promise is completed successfully. 
  2. Rejected : Asynchronous operation corresponding to this promise has failed. Promise will have the reason why it failed. 
  3. Pending : The asynchronous operation is still pending and is neither in fulfilled or rejected state.
  4. Settled : This is a generic state. Asynchronous operation is complete and can be in - Fulfilled or Rejected state.
A state will be in pending till the asynchronous operation is in progress. Once it is complete state can be fulfilled or rejected and from then state cannot change. 

NOTE : We are saying asynchronous operation because general processed are asynchronous for which promise are created. But it need not be. Promise may correspond to a synchronous operation as well.

Consider a simple promise as follows -


var testPromise = new Promise(function(resolve, reject){
        //your test operation - can be async
        let testSuccess  = true; // can be false depending on if your test async operation failed  
        if(testSuccess) {
                resolve("success");
        }
        else {
                reject("failure");
        }
});

testPromise.then(function(successResult){
        console.log("Test promise succeded with result : " + successResult);
}).catch(function(failureResult){
        console.log("Test promise failed with result : " + failureResult);


This prints output : Test promise succeded with result : success
You can change testSuccess to false and it will print : Test promise failed with result : failure

So let's see what happened here. 
  • First we created a new promise with constructor new Promise()
  • constructor takes an argument as function that basically defines what operation needs to be performed as part of that promise
  • This function takes two callbacks -
    • resolve()
    • reject()
  • You will call resolve() when your operation is successful and will call reject when it fails. resolve() will essentially put the promise in Fulfilled state where as reject will put it in Rejected state ww saw above.
  • Depending on result of our operation (can be asynchronous) we will call resolve() or reject()
  • Once promise object is created we can call it using then() method of promise object. then() method will be called when promise is fulfilled and catch() method will be called when it is rejected/failed.
  • You can toggle the value of testSuccess boolean and see for yourself.
  • Each then() and catch() take an argument which is nothing but variable passed by resolve() and reject() which in this case is success or failure

Now that we know what promise is and how it behaves lets see if this can solve our synchronisation problem. We have 3 asynchronous operations and we need to do it one after the other -


var test1 = new Promise(function(resolve,reject){
        resolve('test1');
});
var test2 = new Promise(function(resolve,reject){
        resolve('test2');
});
var test3 = new Promise(function(resolve,reject){
        resolve('test3');
});


test1.then(function(test1Result){
        console.log('completed : ' + test1Result);
        return test2;
}).then(function(test2Result){
        console.log('completed : ' + test2Result);
        return test3;
}).then(function(test3Result){
        console.log('completed : ' + test3Result);
});


This one outputs - 
completed : test1
completed : test2
completed : test3

Only difference here is in each then function we are returning next promise and calling then on it so that it is run sequentially.

Alternatively you can also do -

var test1Func = function() {
        return test1;
};
var test2Func = function() {
        return test2;
};
var test3Func = function() {
        return test1;
};
test1Func().then(function(test1Result){
        console.log('completed : ' + test1Result);
        return test2Func();
}).then(function(test2Result){
        console.log('completed : ' + test2Result);
        return test3Func();
}).then(function(test3Result){
        console.log('completed : ' + test3Result);
});

Now what if I want to do some task when all three promises are done. For that you can do -

Promise.all([test1Func(),test2Func(),test3Func()]).then(function(){
        console.log('All tests finished');
});


And this will output - All tests finished

Similarly if you want to do something if any one of the promise is complete you can do -


Promise.race([test1Func(),test2Func(),test3Func()]).then(function(){
        console.log('All tests finished');
});

and this will output - One of the tests finished

To sum it up promise looks like below -



Related Links

Sunday, 18 December 2016

Greasemonkey script to dim white background webpages in Firefox

Background

In some of the previous posts we saw some greasemomkey scripts -
 This is a similar script.

Bright white pages strain your eyes. I love dark black/grey themes and they dont strain your eyes as well. So was looking out for an addon to do this.
Chrome has a beautiful addon called -
Unfortunately there is no such good plugin available on Firefox. Hence this script. You can configure RGB to the background color you wish to have. The script will be executed when your DOM(Document object model) is loaded.

Greasemonkey script to dim white background webpages in Firefox

I am not going to paste the code here. It is available on my Github gists page -
Feel free to fork it and change it as per you need. Google homepage looks like below post this change -


It has sort of greyish background.


NOTE : This is not a script originally written by me. I have just modified it to suit my needs. Feel free to edit it and use as per your requirements.

Related Links

Saturday, 11 June 2016

Greasemonkey script to replay Youtube videos once they finish

Background

In one of the previous post we saw a Greasemonkey script to block Game of thrones spoiler on facebook.  In this post we will see Greasemonkey script to replay Youtube videos once they finish. And we will see how to do this from very beginning including installing the plugin.



Setup

First step is to install the  Greasemonkey  plugin in firefox. There is a similar plugin in chrome called Tampermonkey. For demo purposes we will use firefox. So go ahead and install the plugin. URL is -




Once installed you can see it's icon besides navigation bar. There you can click to create a new user script -



Then you should see a window where you can create your script.



You can find the actual script on my github account - 

Related Links

Sunday, 29 May 2016

Greasemonkey script to block Game of Thrones spoilers

Background

Greasemonkey is a Firefox plugin that runs user scripts just like tampermonkey in chrome. In this post we will see a simple script that will blacklist certain words appearing in Game of thrones which will potentially be spoilers.


Greasemonkey script to block Game of Thrones spoilers

Script is as follows -


// ==UserScript==
// @name           Spoiler Killer
// @include        http://*.facebook.com/*
// @include        https://*.facebook.com/*
// @require        http://code.jquery.com/jquery-1.7.1.min.js
// @require        https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant          none
// @version 1
// @namespace http://opensourceforgeeks.blogspot.in/
// @description Blacken facebook posts possibly containing Game of Thrones spoilers.
// copied from https://gist.github.com/vshivam/94d18c5d652217a449a5b785cbda1073
// ==/UserScript==

(function(){
    var terms = ['spoiler', 'game of thrones', 'hodor', 'jon snow', 'khaleesi', 'stark', 'dothraki'];
    function actionFunction(node){
        var content = node.html();
        content = content.toLowerCase();
        $.each(terms, function(index, term){
            if(content.indexOf(term) > -1){
                var overlay = $('<div />' ).css({
                     position: "absolute",
                     width: "100%",
                     height: "100%",
                     left: 0,
                     top: 0,
                     zIndex: 1000000,
                     background: "#000000",
                 });
                (function(overlay, node){
                    overlay.appendTo(node.css("position", "relative"));
                    $(node).on("mouseenter", function(){
                        overlay.hide();
                    });
                    $(node).on("mouseleave", function(){
                        overlay.show();
                    });
                })(overlay, node);
            }
        });
    }
    waitForKeyElements("div.userContentWrapper", actionFunction);
})();


NOTE : This script is copied over from https://gist.github.com/vshivam/94d18c5d652217a449a5b785cbda1073.  It's original version can be found at https://gist.github.com/vshivam/9080a0b5ece35689163ed12955c131a9 (simply replaces text)

Script essentially blackens the posts that contain spoiler words. Feel free to add/remove words as you choose suitable. Make sure that the script is running on the site you intend it to be. You can test that from  Greasemonkey icon near URL bar. See following screenshot for details -




Related Links


Tuesday, 10 May 2016

Hide variable from console access - Javascript Closures and self executing functions

Background

I came across javascript closure when I was searching solution for an interesting question - can variable be private in javascript. Let me give an example to demonstrate this further. Consider following Javascript - 


<script>
var counter = 0;

function increment() {
    counter++;
    console.log('After increment counter : ' + counter);
}

function decrement() {
    counter--;
    console.log(' After decrement counter : ' + counter);
}
</script> 

Now from console in your browser try to access counter variable. You should be able to access it. You can also try to print counter value after executing increment and decrement methods from console.

Couple of notes before we proceed to see the output on console.
  1. In above code counter is a global variable.
  2. In a web page global variables belong to window object. So you can also access it using window.counter.
  3. Global variables can be accessed/changed by all scripts in a page.
  4.  A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.
  5. Global and local variables with the same name are different variables. Modifying one, does not modify the other.  
  6. Variables created without the keyword var, are always global, even if they are created inside a function.

Now the question is we don't want to expose counter variable. What can we do? Closures to the rescue.

Javascript closure

Now see the javascript code below - 

<script>

var increment, decrement, printCounter;

(function () {
    var counter = 0;
    increment = function() {
        counter++;
        console.log('After increment counter : ' + counter);
    };
    decrement = function() {
        counter--;
        console.log(' After decrement counter : ' + counter);
    };
    printCounter = function() {
        console.log('counter : ' + counter);
    };
})();

</script>

Now repeat above operation. You cannot access counter variable now. Since it is define inside the closure it's scope is limited to that. functions on the other hand are global, so those you can use.


Noticed the following syntax?

(function(){
    //Bunch of code...
})();


It's called self executing function. It is executed only once when page loads.



So A closure is a function having access to the parent scope, even after the parent function has closed. 
If you just have one method you can also do something like -

 var increment = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

increment();
increment();
increment();
// the counter is now 3 



Related Links

Sunday, 15 November 2015

Create your own chrome plugin example demo

Background

In this post we will see how to create chrome plugins. We will see a simple demo plugin example in which when we click on the plugin icon we will will see the URL of current active TAB.


Getting Started

Create a directory where you will create files needed for your plugin. Lets call it "chrome_plugin" directory. 
  • First and foremost what you need is a file called manifest.json. This file essentially tell chrome browser details about your plugin like it's name, it's version, what permission it needs and the actual code files.

For our demo this file looks something like below -

{

  "manifest_version": 2,
  "name": "Open Source For Geeks Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },

  "permissions": [
   "activeTab"
   ]

} 


Contents of manifest.json file are basically json with plugin details. As you must have notices by now it references two essential resources -
  1. icon.png
  2. popup.html
  • Go ahead and put icon.png and create a file called popup.html is the same directory - "chrome_plugin".




 If you do not have the icon you can use the one above. It's 20*20 pixels icon.

  • Next edit popup.html with following contents - 

<!doctype html>

<html>
  <head>
    <title>OSFG Chrome Demo Plugin</title>
    <script src="popup.js"></script>
  </head>
  <body>

    <h1>Current Site URL : </h1>
    <br/>
    <div id="currentTabUrl"></div>
  </body>
</html>


Again a simple HTML file but note it asks to load a popup.js javascript file.

  •  Go ahead create a file called popup.js and add following contents to it -

function getCurrentActiveTabUrl(callback) {

  var tabQueryInfo = {
    active: true,
    currentWindow: true
  };

  chrome.tabs.query(tabQueryInfo, function(tabs) {
    var currentTab = tabs[0];
    var url = currentTab.url;]
    console.log(url);
    console.assert(typeof url == 'string', 'currentTab.url should be a string');
    callback(url);
  });

}
  

function renderOutput(outputText) {
  document.getElementById('currentTabUrl').innerHTML = "<a href='" + outputText + "'>" + outputText + "</a>";
}

document.addEventListener('DOMContentLoaded', function() {
  getCurrentActiveTabUrl(function(url) {
        renderOutput(url);
  });
});



Take some time to see the javascript code above. It essentially reads the current active TAB url and shows it in the popup in an anchor tag. And there you go your first chrome plugin is all set to be deployed.

NOTE : Most of the chrome APIs are asynchronous. So you cannot do something like -

var currTabUrl;
chrome.tabs.query(queryInfo, function(tabs) {
  currTabUrl= tabs[0].url;
});
alert(currTabUrl); // Will show "undefined" as chrome.tabs.query is async.


Deploying your chrome plugin

Deploying your plugin is again quite simple
  • Go to chrome://extensions/ URL is your chrome browser. Here you should see list of existing chrome extensions you are using.
  • Make sure "Developer Mode" check box is selected.

  • Now click on "Load Unpacked Extension" and select the folder you have plugin in - "chrome_plugin" directory is this case.

  • Now open any tab. You should see the plugin with icon you had put in the directory just besides Omnibox. Go to any URL and then click on the plugin icon.  



 You can download this sample chrome plugin code from here.

Appending custom methods to chrome right click Menu

Lets see how we can add custom functions to right click menu. Here is what we are going to do -  we will add a new option on right click which enables to search selected text in google maps.


The new manifest.json file looks like the following - 

{
  "manifest_version": 2,

  "name": "Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",
  
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab",
   "contextMenus"
   ]
}

Notice couple of differences here
  1. There is a new permission added called contextMenus. This basically lets you operator om chrome context menus.
  2. There is a new key added called background that basically tells chrome about background processes. You can specify scripts or page here.
 Next in background.js add following code

function searchgooglemaps(info)
{
 var searchstring = info.selectionText;
 chrome.tabs.create({url: "http://maps.google.com/maps?q=" + searchstring})
}

chrome.contextMenus.create({title: "Search Google Maps", contexts:["selection"], onclick: searchgooglemaps});


 And you are done. Reload the extension.



When you click on "Search Google Maps" you should see a new Tab opening with google maps and a search location of your desired selected String.


Related Links

t> UA-39527780-1 back to top