Sunday, April 1, 2018

JavaScript Currying in ES5 and ES6

  1. It is a mechanism of evaluating function with multiple parameters into sequence of functions with single parameter. It means, Instead of passing all parameters at one time, takes first parameter and return a new function that takes second and return a new function, until all parameters have been fulfilled. 
  2. It is useful to create reusable event handling code 
  3. It is helpful to avoid passing same variable again and again 
  4. It is helpful to create a higher order function
ES5 Normal Function
var say = function(wish, name) {
  console.log(wish + ", " + name);
};
say("Hi", "Nolan");  // output :  Hi,Nolan

Convert above function into nested function

ES5 Currying Function
var saycurrying = function(wish) {
  return function(name) {
    console.log(wish + ", " + name);
  };
};
var sayHi = saycurrying ("Hi");
sayHi ("Nolan"); // output : Hi, Nolan
sayHi ("Christopher"); // output : Hi, Christopher

Direct Calling Currying Function
saycurrying(“Hi”)(“Nolan”) // output :  Hi, Nolan

ES5 Currying Function-  Example2
function sum(x) {
  return (y) => {
    return (z) => {
      return x + y + z;
    };
  };
}
var firstparam=sum(2);  /
var secondparam = firstparam(3);
var result = secondparam(4);  // output : 9

Direct calling:  sum(2)(3)(4); // output : 9

ES6 Currying Function-  Example1
var saycurrying = (wish) => (name) => {
    console.log(wish + ", " + name);
  };
var sayHi = saycurrying ("Hi");
sayHi ("Nolan"); // output : Hi, Nolan

Direct calling: saycurrying ("Hi")(“Nolan”); // output : Hi, Nolan

ES6 Currying Function-  Example2
renderHtmlTag = tagName => content => `<${tagName}>${content}</${tagName}>`
renderDiv = renderHtmlTag('div')
renderDiv(“This is sample div”)
renderH1 = renderHtmlTag('h1')
renderH1 (“This is sample H1”)

Direct calling: renderHtmlTag("div")(“This is sample div”); 

Happy Coding :)

Sunday, February 25, 2018

JavaScript : ES6 Import, Export Modules

1. Prior to ES6, we use to implement modules using libraries. But, ES6 comes with built-in modules
2. ES6 modules are stored in files. There is exactly one module per file and one file per module
3. ES6 comes with named Export and default exports
4. It should be only one default export in a single JavaScript file
5. It can contain one or more named exports in single JavaScript file
6. We should not write conditional export and import
7. Imports are hoisted. So, it doesn’t matter where you write import statement in a file

Default Exports (one per module)
  1. There should be only one default export per module/ file 
  2. We can implement default export by prefixing the declaration with the keyword “default” 
            Create a file “TestModule.js” and add following content

                        //------------ TestModule.js ---------------- //

                     export default function() { return 10 + 10 }; 

          If you want to use this function in “Main.js” file, add following content 

                       // ------------ Main.js ------------------------ // 

                       import TestModule from ‘TestModule’
                       console.log(TestModule()); 

Note : Here, we are using module name/file name for importing function

Named Exports (one or more per module)

  1.  We can export multiple things like function, const, class and etc by prefixing their declarations with the keyword “export” 
  2. These exports are differentiated by their names called named exports 
  3. Use curly braces while importing 
       Create a file “TestModule.js” and add following content

                    //------------ TestModule.js ---------------- // 

export function AddNum(num1,num2) { return num1 + num2 };
export const PI=3.14;

If you want to use these in “Main.js” file, add following content

                        // ------------ Main.js ------------------------ //

import { AddNum, PI } from ‘TestModule’
console.log(AddNum(10,10)); console.log(PI);

Mixed named and default Exports
  1.  We can combine both default and named exports in a single module
            Create a file “TestModule.js” and add following content

               //------------ TestModule.js ---------------- //
 
export function AddNum(num1,num2) { return num1 + num2 };
export const PI=3.14;
export default function(){return 10}

If you want to use these in “Main.js” file, add following content

// ------------ Main.js ------------------------ //

import TestModule, { AddNum, PI } from ‘TestModule’
console.log(AddNum(10,10));
console.log(PI);
console.log(TestModule());

named export with alias name

Create a file “TestModule.js” and add following content 

//------------ TestModule.js ---------------- //

export function AddNum(num1,num2) { return num1 + num2 };
export { AddNum as AddTwoNum }

If you want to use these in “Main.js” file, add following content

// ------------ Main.js ------------------------ //

import { AddTwoNum } from ‘TestModule’
console.log(AddTwoNum (10,10));

default import with alias name

Create a file “TestModule.js” and add following content 

//------------ TestModule.js ---------------- //

export default function() { return 10 + 10 };

If you want to use this function in “Main.js” file, add following content

// ------------ Main.js ------------------------ //

import { default as AddTwoNum } from ‘TestModule’
console.log(AddTwoNum ());

named import with alias name

Create a file “TestModule.js” and add following content

//------------ TestModule.js ---------------- //

export function AddNum(num1,num2) { return num1 + num2 };
export const PI=3.14;

If you want to use these in “Main.js” file, add following content

// ------------ Main.js ------------------------ //

import { AddNum as AddTwoNum, PI as PIVal } from ‘TestModule’
console.log(AddTwoNum (10,10));
console.log(PIVal);

namespace import

Create a file “TestModule.js” and add following content

//------------ TestModule.js ---------------- //

export function AddNum(num1,num2) { return num1 + num2 };
export const PI=3.14;

If you want to use these in “Main.js” file, add following content

// ------------ Main.js ------------------------ //

import * as TestLib from ‘TestModule’
console.log(TestLib .AddTwoNum (10,10));
console.log(TestLib .PIVal);

Combine default import with namespace import

Create a file “TestModule.js” and add following content 

//------------ TestModule.js ---------------- //

export function AddNum(num1,num2) { return num1 + num2 };
export const PI=3.14;
export default function(){return 10} ;

If you want to use these in “Main.js” file, add following content 

// ------------ Main.js ------------------------ //

import TestModule, * as TestLib from ‘TestModule’
console.log(TestLib .AddTwoNum (10,10));
console.log(TestLib .PIVal);
console.log(TestModule());

Happy Coding :)

Saturday, February 24, 2018

JavaScript: ES6 Arrow Functions

1. It is also called “fat arrow” =>
2. These is more concise syntax for writing expressions
3. It doesn’t have its own “this”
4. These are anonymous and change the way “this” binds in functions
5. By using arrow function we can avoid having to type the function keyword, return keyword, and curly brackets ( i.e. it is implicit )

Arrow Function with One Parameter

Traditional Way

function test(param) { return param+10; }
test(10);

New Way

var test=(param) => param + 10 ;
test(10);

Arrow Function with Multiple Parameters

Traditional Way

function test(param1,param2) { return param1 + param2; }
test(10,10);

New Way

var test=(param1, param2) => param1 + param2 ;
test(10,10);

Arrow Function without Parameters

Traditional Way

function test() { return 10; }
test();

New Way

var test=() => 10 ;
test();

Arrow Function with Multiple Statements

Traditional Way

function test() {
      var p1=10;
      var p2=20;
      return p1+p2;
 }
test();

New Way

var test=() => {
       let p1=10;
       let p2=20;
      return p1+p2;
}
test();

Arrow Function with Object

Traditional Way

function test(name,email) {
    return
      {
          Name: name,
          Email: email
      };
  }
test(‘rama’,’rama@gmail.com’);

New Way

var test=(name,email) => ({ Name:name, Email:email});
test(‘rama’,’rama@gmail.com’);

Happy Coding :)

Saturday, January 6, 2018

C#.NET Equality : Equals() , == operator and ReferenceEquals()

There are actually two basic types of equality for objects

1. Value Equality : Two objects are equivalent if the value contains same
2. Reference Equality: Two objects are identical if it is pointing to same memory address location

1. a.Equals(b)
a)      Equals() is a virtual method on System.Object
b)      It checks  value comparison for Value Types
c)       It checks value comparison for string Type ( i.e. System.String overridden Equals() method to do value comparison )
d)        It checks memory address comparison for Reference Type
e)      It throws NullReferenceException exception when object a is null

public class StudentTest
    {
        public int Id { getset; }
        public string Name { getset; }
    }

            int a = 10;
            int b = 10;
            Console.WriteLine(a.Equals(b)); // True

            StudentTest stdObj1 = new StudentTest() {Id=1,Name="Nolan" };
            StudentTest stdObj2 = new StudentTest() { Id = 2, Name = "James" };

            Console.WriteLine(stdObj1.Equals(stdObj2)); // False

            StudentTest stdObj3 = stdObj2;
            Console.WriteLine(stdObj3.Equals(stdObj2)); // True


2. object.Equals(a,b)
a)      It is a static method (i.e. simple helper method ) on the object class
b)      It does null check before comparison so, it will not throw NullReferenceException exception when object a or b is null
c)       It returns True if both objects are null
d)      It checks  value comparison for Value Types
e)      It checks value comparison for string Type ( i.e. System.String overridden Equals() method to do value comparison )
f)         It checks memory address comparison for Reference Type
g)      It is same as a.Equals(b) except NullReferenceException Handling

            int a = 10;
            int b = 10;
            Console.WriteLine(object.Equals(a, b)); // True
 
            StudentTest stdObj1 = new StudentTest() { Id = 1, Name = "Nolan" };
            StudentTest stdObj2 = new StudentTest() { Id = 2, Name = "James" };
 
            Console.WriteLine(object.Equals(stdObj1, stdObj2)); // False
 
            StudentTest stdObj3 = stdObj2;
            Console.WriteLine(object.Equals(stdObj3, stdObj2)); // True
 
            StudentTest stdObj4 = null;
            StudentTest stdObj5 = null;
            Console.WriteLine(object.Equals(stdObj4, stdObj5)); // True

3. object.ReferenceEquals(a, b)

a) It checks memory address comparison for both Value and Reference Type
b) It expects two object type parameters. So, Passing value Types gets boxed into heap
and stored into two different memory address locations


int a = 10;
int b = 10;
Console.WriteLine(object.ReferenceEquals(a, b)); // False

int c = b;
Console.WriteLine(object.ReferenceEquals(c, b)); // False

object val1 = 10;
object val2 = val1;

Console.WriteLine(object.ReferenceEquals(val1, val2)); // True


StudentTest stdObj1 = new StudentTest() { Id = 1, Name = "Nolan" };
StudentTest stdObj2 = new StudentTest() { Id = 2, Name = "James" };

Console.WriteLine(object.ReferenceEquals(stdObj1, stdObj2)); // False

StudentTest stdObj3 = stdObj2;
Console.WriteLine(object.ReferenceEquals(stdObj3, stdObj2)); // True

StudentTest stdObj4 = null;
StudentTest stdObj5 = null;
Console.WriteLine(object.ReferenceEquals(stdObj4, stdObj5)); // True

4.      a == b
a)      It is an operator ( == ) works same as a.Equals(b)
b)      It checks  value comparison for Value Types
c)       It checks value comparison for string Type ( i.e. System.String overridden Equals() method to do value comparison )
d)        It checks memory address comparison for Reference Type

int a = 10;
int b = 10;
Console.WriteLine(a == b); // True

StudentTest stdObj1 = new StudentTest() { Id = 1, Name = "Nolan" };
StudentTest stdObj2 = new StudentTest() { Id = 2, Name = "James" };

Console.WriteLine(stdObj1 == stdObj2); // False

StudentTest stdObj3 = stdObj2;
Console.WriteLine(stdObj3 == stdObj2); // True

StudentTest stdObj4 = null;
StudentTest stdObj5 = null;
Console.WriteLine(stdObj4 == stdObj5); // True

Note:  We can provide custom equality comparison by Implementing IEquatable interface

Happy Coding :)