A few Javascript Gotchas

Regular Equality vs Strict Equality.

{} === {}

false // Even though they are empty objects, strict equality not only checks for type & value, but also checks the created instance. The created instance is different for each new Object

{} == {}
false

{x:5} == {x:5}
false

{x:5} === {x:5}
false

0 === false
false

0 == false
true

0 == 0
true

0 === 0
true

1 == 1
true

1 === 1
true

new Object() == new Object()
false

new Object() === new Object()
false

Object.create([]) === Object.create([])
false

Object.create([]) == Object.create([])
false

var x =””;
if(x){console.log(“123”)} else{console.log(“456”)}
456

var x = [];
if(x){console.log(“123”)} else{console.log(“456”)}
123

“” == 0
true

[] == “”
true

“” === 0
false

[] === “”
false

“” == ”
true

“” === ”
true

typeof(”)
“string”

typeof(“”)
“string”

” instanceof String
false

“” instanceof String
false

new String(“”) instanceof String
true

typeof(new String())
“object”

“”.toString == new String(“”)
false

“”.toString() == new String(“”)
true

“”.toString() == new String(“”).toString()
true

“”.toString === new String(“”)
false

“”.toString() === new String(“”)
false

“”.toString() === new String(“”).toString()
true

[] == new Array[];
VM362:1 Uncaught SyntaxError: Unexpected token ]

[] === new Array[];
VM363:1 Uncaught SyntaxError: Unexpected token ]

typeof(“”)
“string”

typeof(”)
“string”

typeof([])
“object”

typeof(Object)
“function”

typeof(new Array())
“object”

typeOf(new Array()) // typeOf is not defined, O in red is capital
VM418:1 Uncaught ReferenceError: typeOf is not defined(…)(anonymous function)

[].constructor.toString().indexOf(“Array”) > -1
true

[] instanceof Array
true

typeof null
“object”

typeof {}
“object”

{} instanceof Object
VM1270:1 Uncaught SyntaxError: Unexpected token instanceof

var t = {}
t instanceof Object
true

Object instanceof t
VM1385:1 Uncaught TypeError: Right-hand side of ‘instanceof’ is not callable(…)

typeof undefined
“undefined”
Note that typeof undefined is undefined which is wrapped in string quotes, but not a string.

typeof (typeof undefined)
“string”
Since the (inner) typeof undefined is undefined wrapped in string quotes, and the (outer) typeof (“undefined”) is being assumed as a string.

typeof when variable is defined.

var d = {};

typeof d === undefined
false

typeof d === “undefined”
false

d === “undefined”
false

d === undefined
false

typeof when variable is not defined

typeof u === undefined
false

typeof u === “undefined”
true

u === “undefined”
VM455:1 Uncaught ReferenceError: u is not defined
at <anonymous>:1:1
(anonymous) @ VM455:1

u === undefined
VM458:1 Uncaught ReferenceError: u is not defined
at <anonymous>:1:1

Numbers

1/-0 > 0
false

1/-0
-Infinity

-Infinity == 0
false

-Infinity > 0
false

-Infinity === 0
false

-Infinity > 1
false

-Infinity == 1
false

-Infinity === 1
false

Infinity == NaN
false

Infinity === NaN
false

1 instanceof Number
false

1/0 instanceof Number
false

1/0
Infinity

Infinity instanceof Number
false

typeof(“”)
“string”

typeof(Infinity)
“number”

new Number(1) instanceof Number
true

99.99 instanceof Number
false

typeof(99.99)
“number”

new Number(99.99) instanceof Number
true

typeof(NaN)
“number”

NaN instanceof Number
false

new Number(NaN)
Number {[[PrimitiveValue]]: NaN}

new Number(NaN) instanceof Number
true

NaN == Number
false

NaN === Number
false

new Number(NaN) === Number
false

new Number(NaN) == Number
false

NaN == undefined
false

NaN === undefined
false

NaN === ”
false

NaN == ”
false

NaN == null
false

NaN === null
false

isNaN(NaN)
true

Objects/Functions

var e = function(){};
var r = function(){};
var e1 = new e();
var r1 = new r();

e == r
false

e === r
false

typeof e
“function”

e instanceof function
VM352:1 Uncaught SyntaxError: Unexpected end of input

function instanceof e
VM387:1 Uncaught SyntaxError: Unexpected token instanceof

e1 == r1
false

e1 === r1
false

e1 instanceof r1
VM750:1 Uncaught TypeError: Right-hand side of ‘instanceof’ is not callable(…)(anonymous function) @ VM750:1

e1 instanceof Function
false

e1 instanceof Object
true

typeof(e1)
“object”

Assignments

var a = [1,2,3];
var b = [4,5,6];

a = b
[4, 5, 6] // This the value of a

a
[4, 5, 6] // a assignment to b copied over all values of b

b
[4, 5, 6] // No changes to b, so b still had reference to its original values

Pass by reference/value

var func = function(a) { var tempArray = [4,5,6];   a = tempArray;   console.log(a);}

func([1,2,3]);

[4,5,6] // Even though we pass by reference with a different value, the assigned variable value would be overridden with internal assignment (if any).

Which is best to use: typeof or instanceof?

http://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof

Advertisements

Area, Perimeter and Type of a Triangle.

Problem Statement: Given 3 sides of a triangle, find the area, perimeter and determine the type of the triangle, if isosceles, equilateral, or scalene. Also, check for Right Angled Triangle. /*Skipping Acute and Obtuse triangle types.*/

Prompt 3 user inputs for sides of the triangle and a dialog to output.

Solution:

import javax.swing.JOptionPane;

public class Triangle {

	/**
	 * This is a class to determine if the given side lengths form a triangle.
	 * It lets the user know the type of the triangle based on the given side lengths.
	 * Also, it gives the Perimeter and Area of the triangle.
	 * @param args
	 */
	public static void main(String[] args) {

//		String sideA, sideB, sideC;
		double a,b,c;
		a = Double.parseDouble(JOptionPane.showInputDialog(null,"Please input side 1 length of the triangle: ", "Triangle Side 1", JOptionPane.QUESTION_MESSAGE));
		b = Double.parseDouble(JOptionPane.showInputDialog(null,"Please input side 2 length of the triangle: ", "Triangle Side 2", JOptionPane.QUESTION_MESSAGE));
		c = Double.parseDouble(JOptionPane.showInputDialog(null,"Please input side 3 length of the triangle: ", "Triangle Side 3", JOptionPane.QUESTION_MESSAGE));
		
		// For right angled triangle, as per mathematics, square of the hypotenuse is equal to the sum of the squares of the other 2 sides. h^2 = a^2 + b^2 where h is hypotenuse (can be any side a,b,c)
		// So we first need to determine the hypotenuse
		
		double h = a > b ? (a > c ? a : c) : (b > c ? b : c);
		
		// Permiter of the triangle
		double p = a + b + c, s = p/2;
		
		//Area of triangle
		double areaOfTriangle = Math.sqrt(s * (s-a) * (s-b) * (s-c));
		
		// Check to see if the triangle is equilateral -- All sides should be equal
		if(a == b && b == c){ // no need to check a == c the value always holds true.
			JOptionPane.showMessageDialog(null, "Based on the given sides, the triangle is a equilateral." +
					"\nPerimeter of the triangle is " + p + 
					"\nArea of Triangle is " + areaOfTriangle);
		} 
		// Check to see if the triangle is isosceles -- At least 2 sides should be equal
		else if(a == b || b == c || c == a) {
			JOptionPane.showMessageDialog(null, "Based on the given sides, the triangle is a isosceles." +
					"\nPerimeter of the triangle is " + p + 
					"\nArea of Triangle is " + areaOfTriangle);
		}
		// Check to see if the triangle is right angle -- Can be verified if sum of squares of each of the sides is equal to twice the square of the hypotenuse. 
		//Ex : 3^2 + 4^2 + 5^2 = 2 * h^2 where h is the hypotenuse
		else if(Math.pow(h,2) * 2 == Math.pow(a,2) + Math.pow(b,2) + Math.pow(c,2)) {
			JOptionPane.showMessageDialog(null, "Based on the given sides, the triangle is a right angled triangle." +
					"\nPerimeter of the triangle is " + p + 
					"\nArea of Triangle is " + areaOfTriangle);
		}// Check to see if the triangle is scalene -- no sides should be equal
		else if(a != b && b != c && a != c) {
			JOptionPane.showMessageDialog(null, "Based on the given sides, the triangle is scalene." +
					"\nPerimeter of the triangle is " + p + 
					"\nArea of Triangle is " + areaOfTriangle);
		}
		// Check if the triangle is not a triangle
		else if(a > b + c || b > a + c || c > a + b ) {
			JOptionPane.showMessageDialog(null, "Based on the given sides, the triangle is not a triangle");
		}
		else {
			JOptionPane.showMessageDialog(null, "Based on the given sides, the triangle is a normal triangle." +
					"\nPerimeter of the triangle is " + p + 
					"\nArea of Triangle is " + areaOfTriangle);
		}
	}

triangle

 

mailto: protocol with attachment in javascript?

Hello Folks,

It’s been quite a while I haven’t word pressing. I wanted to take some time out to blog a few helpful coding tips & tricks that I am coming across these days.

A few days back, my colleague had a requirement on opening a Outlook email using simple javascript which also includes a attachment to the outlook email. Well google’ing a bit found the answer to do so, but including a attachment to that is being hosted on a different server (OnBase Document Server) was a challenge.

Clicking this button below opens the Mail Draft Dialog Window (Mail is a default application for eMails in Mac OSX) / Outlook Draft Dialog Window (if Windows OS), with user set TO (sent by) email address, Subject Line (Outlook takes in maximum of 255 characters on Subject Line), Message Body. Note that the FROM (received from) email address will be decided by the default account set in Mail App/Outlook App.

mailTo

<a href="mailto:rc@rakeshchouhan.com?subject=Test%20Mail-To-Talk"></a>
According to RFC 2368 you can’t add an attachment to a message with the mailto: URL scheme due security reasons:

The user agent interpreting a mailto URL SHOULD choose not to create a message if any of the headers are considered dangerous; it may also choose to create a message with only a subset of the headers given in the URL. Only the Subject, Keywords, and Body headers are believed to be both safe and useful.

Conclusion:

mailto: only supports header values or text/plain content.

 

Happy learning 🙂

Convert a Maven project to eclipse project..

Given that a project is built in Maven, and you would like to import the same project in eclipse IDE. Or sometimes developers intentionally do not check in .project, .settings files to the repository. These files are generated by the eclipse IDE.

cd to the project directory

mvn eclipse:eclipse

Note: ensure that the project directory has pom.xml

Pascal’s Triangle with O(n^2) worst case.

public class PascalTriangle {
    
    public static void main(String[] args) {
        showPascal(9);
    }
    
    // This takes O(n^2) constraint.
    public static void showPascal(int rows){
    	// rows = Number of Pascal triangle rows to show up
    	// i = loop thru each row.
    	for(int i = 0; i<rows; i++)
    	{
    		// Start from 1. So, initialize the first number to 1
    		int number = 1;
    		// Give the spacing - Ex: If rows is 9, then the spacing  would 18 (because I specified the args as "", else if I specify args as "_", you would notice that the spacing is 17 and on 18th bit there would be a '_' ) for the first iteration of i = 0.
    		System.out.format("%"+(rows-i)*2+"s", "");
    		// j = loop thru  each column of a row by CALCULATing and display
    		for(int j=0; j<=i; j++)
    		{
    			// Give 3 more spacing and print the number on the 4th bit.
    			System.out.format("%4d", number);
    			
    			// Formula to calculate each column.
    			number = number * (i - j)/(j + 1);
    		}
    		// Print a empty line after each row.
    		System.out.println();
    	}
    }

Here is how the output look like:

pascaltriangleoutput

Happy Coding !!!

DB2 – Drop Table “IF EXISTS”

Hello Folks,

As most of you may probably be aware that DB2 does NOT have a “If Exists” check safe keyword to safely execute the DML statements.

Here is one another way apart from the many ways one would find over the net.

BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE ‘{SQL_STATE}’
BEGIN END;
EXECUTE IMMEDIATE ‘DROP TABLE {SCHEMA_NAME.TABLE_NAME}’
END
GO

This query is fail safe, meaning that it captures the SQL State error if the statement failed to execute and continuous with other below statements, if any.

Here the SQL_STATE can be found at http://www.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/codes/src/tpc/db2z_sqlstatevalues.html

and SCHEMA_NAME.TABLE_NAME is self explanatory.

Happy Learning !!