Wednesday, December 13, 2017

Some basic JavaScript String concepts

Basic and Best things to know work with JavaScript Strings:

1. String replace

The replace function will help to replace any string operation. It will replace string for the first occurrence only.

So by going with regex its so simple and your quality of code will be good.

let first = " I want to replace first as second , but here first comes in many places";

first.replace(/first/g,"second")

" I want to replace second as second , but here second comes in many places"

2. Template String

In ES6, we have an option to use template string which will give an option to modify the string within it. Example below.


let templateSecond = "I am waiting for you!"
`Hi Monisha ${templateSecond}`
"Hi Monisha I am waiting for you!"

3. Includes

If you want to find whether particular string is available or not in the current string. Use like below

let includeChck ="ABC, DEF, GHI, JKL, MNO"
includeChck.includes("GHI") //Output : true

includeChck.includes("GHIS") //Output : false

4. String to Number


let strToNum = "1234576"
parseInt(strToNum) // Output: 1234576

let str = "123488bcd34"
parseInt(str)    //Output: 123488

Remember if character placed after number it will not consider.

The same thing can apply to parseFloat also.

5. setInterval and setTimeout

While passing function to setInterval and setTimeout do not use string quotes. Use without quotes, so that it can bring better performance.

Else eval function will be executed it makes process time to slow.

//Wrong Format
setInterval('doSomethingPeriodically()', 1000);  
setTimeout('doSomethingAfterFiveSeconds()', 5000);


//Correct Format
setInterval(doSomethingPeriodically, 1000);  
setTimeout(doSomethingAfterFiveSeconds, 5000);

Thursday, November 23, 2017

Builder design pattern simple example

The below is normal simple class with constructor.

public class Computer {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public Computer(String modelname, int ram, String keyboardName, String mouseName) {
		super();
		this.modelname = modelname;
		this.ram = ram;
		this.keyboardName = keyboardName;
		this.mouseName = mouseName;
	}

	@Override
	public String toString() {
		return "Computer [modelname=" + modelname + ", ram=" + ram + ", keyboardName=" + keyboardName + ", mouseName="
				+ mouseName + "]";
	}
}

You have another one main class called JavaTest is below.

public class JavaTest{
public static void main(String args[]){
Computer comp = new Computer("Intel", 6, "Logitech", "dell");
System.out.println("Comp object is: " + comp );
}
}

Output:
Comp object is: Computer [modelname=Intel, ram=6, keyboardName=Logitech, mouseName=dell]


We can change the above code to Builder design pattern. To do this you need to create one additional class called ComputerBuilder.

public class ComputerBuilder {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public ComputerBuilder setModelname(String modelname) {
		this.modelname = modelname;
		return this;
	}
	public ComputerBuilder setRam(int ram) {
		this.ram = ram;
		return this;
	}
	public ComputerBuilder setKeyboardName(String keyboardName) {
		this.keyboardName = keyboardName;
		return this;
	}
	public ComputerBuilder setMouseName(String mouseName) {
		this.mouseName = mouseName;
		return this;
	}
	
	public Computer getComputer () {
		return new Computer(modelname, ram, keyboardName, mouseName);
	}
}

From the above class,

1. It don't have any getter method. We have added only setter method.

2. The last method getComputer returning the object of Computer class.

Let see how we can execute this code from main class.

Computer c = new ComputerBuilder().setKeyboardName("DELL KEyboard").setMouseName("LOGI Mouse").getComputer();
System.out.println("Comp object from builder design pattern is : " + c );

You can notice from the main class,

1. You wont get complex for creating object for computer.

2. Its not mandatory to put all arguments. If you are not providing arguments it will take its initial initialized value.

3. It will be more clear than our normal code creating object through constructor.

Output:
Comp object from builder design pattern is : Computer [modelname=, ram=0, keyboardName=DELL KEyboard, mouseName=LOGI Mouse]

Thursday, August 3, 2017

How to remove first option from select drop down option value

We may get a task sometime to remove the first value from the drop down like Chosse Country, Empty option, --Select-- etc.,

We can have lot of option to remove this. But here we can use simple css style option. Let see the code.

<select name="test">
    <option value="" style="display: none"></option>
    <option value="">Option 2</option>
    <option value="">Option 3</option>
    <option value="">Option 4</option>
    <option value="">Option 5</option>
  </select>

The style:display:none do the job for you!

UML Diagrams - Notations

Below are the list of notations which we have used in UML diagarms. Let see one by one , so that we can understand while using UML diagrams. 

Actor

It may be a Human user , System or Subsystem etc., Mostly actor will be acted from OUTSIDE.

Object 
 An object - This is a student object and its type is not specified. Underline is must there.

Asynchronous Message
 Its describing an asynchronous action, sender no need to wait for an receiver response. Just assume our normal java async thread flow. The arrow is OPEN.

Boundary
Mostly developers will use this in MVC pattern to mention at screen level. Means, capturing user interactions with system.

Comment 

 Comment , which we can use to describe related to your actions in diagram.

Controller

Controller which is used to mention our MVC pattern controller related to an entity.

DataBase
Database , which is mentioning an back end side to store and retrieve data.

Destroy

Destroy or delete which is mentioning an deleting action. Cross symbol must need to be add to mention its an destroy.

Entity
Entity which is mentioning a Model of  MVC model pattern. Model will capture an information.

Object with Type
Object which is mentioning an instance of type student and its name is s. 


Loop
Loop - Which is mentioning an normal loop with condition.

 Object Without Type
An object named as student and its type is not specified here.

Condition Met
If the condition is met then only it will proceed further.

Return
Return message or response which should be mentioned as dotted lines.

Message Itself

Its used to describe an recursion function. 

Synchronous

A normal synchronous action.

Non Instantaneous
Its describing an amount of time will take to reach other side. Example is network calls.

Friday, July 21, 2017

Editable and searchable Drop down with Javascript

Below is the select drop down, here you able to Edit, Search and Select the value. But forgot to implement arrow icon for the drop down.

However I will do another post which will show you how to hide and show drop down arrow image with the help of css.

Comment below if you need any query.

<html>
<head>
<title>Own Drop Down Component</title>

</head>
<body>
<form name="myfrm">
<input id="filter">
<select id="countries" multiple onchange="onChangeValue()" style="width:11%">
  <option value="india">India</option>
  <option value="america">America</option>
  <option value="germany">Germany</option>
  <option value="russia">Russia</option>
</select>
</form>
<script type="text/javascript">
(function () {
    // the IIFE  for local variable store information
    var optionsCache = [];

    // add option values to the cache with reduce
    function optionsArray(select) {
        var reduce = Array.prototype.reduce;
  //addToCache for cache
        return reduce.call(select.options, function addToCache(options, option) {
            options.push(option);
            return options;
        }, []);
    }
    // give a list of options matching the filter value with match function
    function filterOptions(filterValue, optionsCache) {
        return optionsCache.reduce(function filterCache(options, option) {
            var optionText = option.textContent;
            if (option.text.toLowerCase().match(filterValue.toLowerCase())) {
                options.push(option);
            }
            return options;
        }, []);
    }
    // replace current with new options
    function replaceOptions(select, options) {
 //document.getElementById("countries").size = select.options.length;
        while (select.options.length > 0) {
            select.remove(0);
        }
        options.forEach(function addOption(option) {
            select.add(option);
        });
    }
    
    function filterOptionsHandler(evt) {
        var filterField = evt.target;
        var targetSelect = document.getElementById("countries");
        if (optionsCache.length < 1) {
            optionsCache = optionsArray(targetSelect);
        }
        var options = filterOptions(filterField.value, optionsCache);
        replaceOptions(targetSelect, options);
  var x = document.getElementById("countries").length;
  //alert("bbb"+x)
  if (x > 0) {
  document.getElementById("countries").size = x;
  } else {
   document.getElementById("countries").size = 1;
   var select = document.getElementById("countries");
   select.options[select.options.length] = new Option('No Results','empty');}
    }
    // attach whatever event
    var filter = document.getElementById("filter");
 
    filter.addEventListener( 'click', function(){
  document.getElementById("countries").style.display = "block";
 } );
 filter.addEventListener("keyup", filterOptionsHandler, false);
 document.getElementById("countries").style.display = "none";
}());

function onChangeValue () {
var e = document.getElementById("countries");
var strUser = e.options[e.selectedIndex].text;
//alert(strUser);
  
  if (strUser != null) {
    //alert("Test" + strUser);
 document.getElementById('filter').value = strUser;
 document.getElementById("countries").style.display = "none";
  }
 }
  
</script>
</body>
</html>

Wednesday, July 5, 2017

How to add a particular word starting and end position of notepad++?

1. Press CTRL + H to open Find/Replace Dialog box.

2. Click "Regular expressions" checkbox near to the bottom of the dialog box.

3. Then To add your particular word, "test" (example) to the beginning of each line,
     type `^` in the "Find what" field,
     and "test" in the "Replace with" field. Just click hit "Replace All". (Alt+A Shortcut)

4. To add particular word ,"test" end of each line, type `$` in the "Find what" field,  and "test" in the       "Replace with" field. Then hit "Replace All".

That's All!

Friday, June 16, 2017

Load css based on browser identification

Loading a CSS file based on browser is not a good idea, However I will share the below code to identify browser.

Let it to do by javascript by onload method.

<script type="text/javascript">
 //Short code with ternary
 window.onload = function() {

  var link = document.createElement('link');
  link.rel = "stylesheet";
  link.type = "text/css";

  //Browser Detection
  link.href = (navigator.userAgent.indexOf("Chrome") != -1) ?link.href = "./css/grid.css";
    : (!(window.ActiveXObject) && "ActiveXObject" in window) ? link.href = "./css/iegrid.css";
      : "";
  document.querySelector("head").appendChild(link);
 }
</script>

Some people may document.write method, but It will not work in all case. Since document.write will swipes out the screen. So based on your task situation you should use this.