Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

create-react-app - Create ReactJs Application Tutorial

create-react-app - Create ReactJs Application Tutorial


I have been trying to learn ReactJs and create some sample applications with it. Today found create-react-app (https://github.com/facebookincubator/create-react-app) which will help us to generate sample reactjs application without knowing the reactjs. Only thing we need to do are,

1. Install latest nodejs version.

2. Install create-react-app
npm install -g create-react-app

3. Generate reactjs application using create-react-app
create-react-app myApp

4.       Run the application
cd myApp
npm start

The application will be started at http://localhost:3000.



Make javascript execution synchronus - A Scenario in Angularjs

Make Javascript Execution Synchronous - A Scenario in Angularjs

Last week I came to deal with a problem in my angularjs application. I want to execute a code block only after getting the response from rest service call. This code block is not inside success/failure call back function, but it is below service call code as below.

function function1() {
//rest call
dataService.serviceCall().then(function (data) {
            console.log("label a")
            }, function (error) {
                console.log("call failed"+ error);
                
            });
            
  console.log("label b")
 }

I want to print "label b" only after printing "label a". But now, as javascript is asynchronous, 'label b' is first printed then 'label a'. It is not waiting for the response of the service call.

To print "label b" only after printing "label a", I found two solutions,
1.  Put the label a code inside callback function.
eg :  
function1() {
//rest call
dataService.serviceCall().then(function (data) {

                 console.log("label a");
                printB();
                
            }, function (error) {
                 console.log("call failed"+ error);
             });
            var printB = function(){
                console.log("label b");
            }
        }
In real case, the code block was not a single line code, that's why /i put it outside service call. If it is a small one i could have been included in success callback function it self. Here I moved all the code into a new function in side function itself, so that I will get the all local references. Then I called function inside success callback function. 

I added a new function syncCall. This will call function1. Js promises or deffered is used to make it synchronous. If response is received successfully, 'label a' is printed, promise is resolved and returned. On successful resolution of promise, 'label b' is printed.
eg: 

syncCall();

        function syncCall() {
            var deferred = $q.defer();
            function1(deferred).then(function () {
                console.log("label b");
            }, function () {
                console.log("err");
            });
        }

        /* Filter items */
        function function1(deferred) {
dataService.serviceCall().then(function (data) {

                 console.log("label a");
                deferred.resolve();
                
            }, function (error) {
                 console.log("call failed"+ error);
                deferred.reject();
             });
      return deferred.promise;
        }


Javascript Interview Question


Javascript Interview Question
Today I came across an interesting interview question in javascript.

function testOk(abcd){
return abcd && "ok" ||"not ok";
}

Will this work? What will be the output?

testOk(65)
>>"ok"
testOk(0)

>>"not ok"
testOk("a")
>>"ok"
testOk(true)
>>"ok"
testOk(false)

>>"not ok"

So abcd && "ok" || "not ok"; is equivalent to abcd ? "ok" : "not ok";

The trick here is for &&, it should verify both sides and for ||, it is not required all the time. For || operator, if left part is true, it is not required to process right part.

var abcd = 10;  
abcd == 10 && doSomething(); // is the same thing as if (abcd == 10) doSomething(); 

abcd == 5 || doSomething(); // is the same thing as if (abcd != 5) doSomething();

JavaScript Style Guide by Google


JavaScript Style Guide by Google

Sharing an article having useful information on  JavaScript Style Guides used by Google.

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

Next Version Javascript - ES6 - Harmony

Next Version Javascript - ES6 - Harmony

Interesting article on next version javascript - ECMAScript6, the upcoming version of the ECMAScript standard.
Reference: http://babeljs.io/docs/learn-es2015/#introduction
Code samples : http://www.es6fiddle.net/
ECMAScript 6 compatibility table : http://kangax.github.io/compat-table/es6/
ECMAScript6 is also called as “ES6″, “Harmony” and “ES.next”, which supports Classes, Promises, Octal/Binary numbers and Templates etc.

New features of ES-6 below :

  • Arrows
  • Classes
  • Enhanced Object Literals
  • Template Strings
  • Destructuring
  • Default + Rest + Spread
  • Let + Const
  • Iterators + For..Of
  • Generators
  • Comprehensions
  • Unicode
  • Modules
  • Module Loaders
  • Map + Set + WeakMap + WeakSet
  • Proxies
  • Symbols
  • Subclassable Built-ins
  • Math + Number + String + Object APIs
  • Binary and Octal Literals
  • Promises
  • Reflect API
  • Tail Calls

Object Oriented Javascript using Mozart

Object Oriented Javascript using Mozart

"Do java like programming in javascript." We can develop web applications following OOPs concepts with mozart js. It also helps to develop mvc architecture. Mozart is inheritance library.
It has got following features

  • Simple subclassing.
  • Private and protected methods and properties.
  • Intuitive super method calling.
  • Dynamic getter and setter generation.


Reference: https://github.com/philipwalton/mozart

splice() - Push or pop to array at position


splice() - Add or remove elements to array at position

I have been trying to push an element to array at position. I found splice() method in javascript as a solution.

splice() can be used for adding/removing elements in array at given position.

Array.splice(position, numberOfElementsToRemoveFromPosition, ElementsToPushAtPosition)

Eg:
var array1=[1,2,3,4,5]

Adding at "0" added to 0th position
array1.splice(0,0,0)

array1 -> [0, 1, 2, 3, 4, 5]

Adding "6" at 6th position
array1.splice(6,0,6)

array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing 2 elements from 2nd index , ie removing 2 and 3
array1.splice(2,2)
[2, 3]
array1 -> [0, 1, 4, 5, 6]

adding 2 elements at 2nd index , ie adding 2 and 3
array1.splice(2,0,2,3)
[]
array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing "6" at 6th position and adding "7" and "8"
array1.splice(6,1,7,8)
[6]
array1 -> [0, 1, 2, 3, 4, 5, 7, 8]

References:
http://www.w3schools.com/jsref/jsref_splice.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

_.pluck - Pluck attribute values from array of objects

_.pluck() - Pluck attribute values from array of objects

I came to know a very useful function from underscorejs, _.pluck()  which will return array of attribute values of objects from Array of objects, ie pluck attribute values from array of objects.
eg: var data = [
                {
                    "name": "India",
                    "population": "120",
                    "currency": "Indian rupee",
                    "id": ""
            },
                {
"name": "China",
                    "population": "125",
                    "currency": "Renminbi",
                    "id": ""
            },
                {
                  "name": "USA",
                    "population": "50",
                    "currency": "US Dollars",
                    "id": ""
    }
   ]

  _.pluck(data,"name")
["India", "China", "USA"]

Number Formatting in JavaScript using toLocaleString - Thousand Separator, Currency Formatter

Number Formatting in JavaScript using toLocaleString() - Thousand Separator, Currency Formatter

Today I came across toLocaleString() in javascript which can be used for formatting numbers. Thousand separator, currency formatting etc. can be achieved using this.

var num1= 2000;
num1.toLocaleString();  // "2,000"

 Thousand separator is different for different countries. This is also possible using toLocaleString().

num1.toLocaleString("en-US");
"2,000"
num1.toLocaleString("de-DE");
"2.000"
num1.toLocaleString("ar-EG");
"Ù¢٬٠٠٠"

Currency formatting can also be done.

num1.toLocaleString('ja-JP', { style: 'currency', currency: 'INR' })

"Rs.2,000"

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

lodash - JavaScript utility library delivering consistency, modularity, performance,...

lodash - JavaScript utility library delivering consistency, modularity, performance,...


Today I found a js library just like underscore which has got many useful functions. Check it out.

https://lodash.com/

https://lodash.com/docs

http://devdocs.io/lodash-string/


Difference between setTimeout() and setInterval()

Difference between setTimeout() and setInterval()

1. setTimeout():

setTimeout(
...
function or code
...

, delay);

Function or code will execute after the delay(time interval).

eg: setTimeout(function() { alert('Hi') }, 1000);

2. setInterval():

setInterval(
...
function or code
...

, delay)

Function or code will repeatedly execute for every delay interval(time interval).
eg: setInterval(function() { alert('Hi') }, 1000);

Javascript MemoryLeak Issues

Javascript Memory Leak Issues

We have been facing memory leak issues while developing html5 apps. It is observed that app is broken after browsing through the pages in the app. The memory usage is increased by time. The memory is not released after use. So we searched for some solution and found some technic which will improve memory usage.

1. Nullify the references after use and delete them
Eg: var name1 = someObject;
after scope,
name1 = null;
delete name1;

2. Remove domElements after use(jquery)
var name2 = $("something");
after scope,
name2.remove();

Javascript Format Date, Number and Currency - Moment.js, Numeral.js and Accounting.js

Format Date, Number and Currency - Moment.js, Numeral.js and Accounting.js

I came to know libraries which help us in formatting numbers, dates and currency.

1. Moment.js - To parse, validate, and format dates.

Examples:
moment().format('MMMM Do YYYY, h:mm:ss a'); // April 4th 2015, 3:11:47 pm
moment().format('dddd');                    // Saturday
moment().format("MMM Do YY");               // Apr 4th 15

// selecting time zone
moment.tz("2015-04-04 11:55", "Indian/Mauritius").format(); // "2015-04-04T11:55:00+04:00"
moment.tz("March 12th 2015 8PM", "MMM Do YYYY hA", "Indian/Mauritius").format();
 // "2015-03-12T20:00:00+04:00"


Url: http://momentjs.com/


2. Numeral.js - To format numbers

Examples:
numeral(10000).format('0,0'); // "10,000"
numeral(10000).format('$0,0');  // "$10,000"
numeral(10000).format('0b'); // "10KB"
numeral(0.10).format('0%'); // "10%"

Url: http://numeraljs.com/

3. Accounting.js - To format numbers, money and currency

Examples:
accounting.formatMoney(1000); // "$1,000.00"

// Indian rupee currency formatting
accounting.formatMoney(1000.99, "₹", 2, ".", ","); // "₹1.000,99"

Url: http://openexchangerates.github.io/accounting.js/

Height and Span

Can we set height to span?

Can we set height to span? The answer is no. Span is an inline element. If you provide height to span, there will not be any effect. If you really want to set height then you will have to add  display : inline-block or display : block.

Finding Dimension of Text in Pixels - HTML5 Javascript JQuery

Finding Width & Height of Text in Pixels
HTML5 - Javascript - JQuery

For Div, Span
I came across a problem that i want to find width of the text in my page in order to properly align it. I found the solution using JQuery.
Steps
1. Wrap the text in a span and append to some element say to a div.

$(div).append("<span id='find-length'>"+text+"</span>").

2. Find width and height using JQuery.
var textWidth = $("#find-length").width();
var textHeight = $("#find-length").height();

For SVG
For finding dimension of svg text element we will make use of  getBBox() method.

Eg: var dimension = element.getBBox();
var textWidth = dimension .width;

var textHeight = dimension .height;