Amiya Sahu Developer

Handy JavaScript Utility Methods

Update Object state and return a new object by merging the socond onto the first one

const updateObj = (oldObject, newObject) => {
  return {
    ...oldObject, 
    ...newObject
  };
};

// usage 
let obj = { key1: "value1", key2 : "value2" };
obj = updateObj(obj, { key2 : "value3" });
console.log(obj); // {key1: "value1", key2: "value3"}

How to create singleton instance per thread in java

In case you are new to the term singleton design pattern, It is recommended that, you read this article before proceeding further.

By this time I assume you know the basics and usefulness of a singleton design pattern.

Sometimes we endup in a situation where we can not use the singleton classes in a multiple threaded application. This could be for sevaral reasons like, making use of some data or some instance which are not thread-safe (eg. HashMap).

To create singleton instance per thread, we can make use of a ThreadLocal instance (java doc).

When we invoke get() on a ThreadLocal instance, it returns an independently initialized copy of the variable for each thread. ThreadLocal instances are typically private static fields in classes which we wish to make singleton per thread.

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are garbage collected.

package com.amiyasahu;

public class Singleton {

    private Singleton() {
        // Private constructor
    }

    private static ThreadLocal<Singleton> _threadLocal = 
                new ThreadLocal<Singleton>() {
                    @Override
                    protected Singleton initialValue() {
                        return new Singleton();
                    }
                };

    /**
     * Returns the thread local singleton instance
     */
    public static Singleton getInstance() {
        return _threadLocal.get();
    }
}

If you are using java8 or above, you can replace the _threadLocal definition with below.

_threadLocal = ThreadLocal.withInitial(() -> new Singleton());
                        

Now lets create the test method. Here we will print the instance hashcode with the thread name, so that we can conclude which instance is bound for a thread.

package com.amiyasahu;

import java.util.Random;

public class ThreadLocalTest extends Thread {

    public void run() {
        Singleton instance1 = Singleton.getInstance();
        System.out.println(getThreadName() + instance1);
        sleep(100, 50); // sleep for some time
        Singleton instance2 = Singleton.getInstance();
        System.out.println(getThreadName() + instance2);
        boolean equal = instance1 == instance2;
        String message = equal ? "Both are equal" : "Not equal";
        System.out.println(getThreadName() + message);
    }

    private void sleep(int max, int min) {
        try {
            int time = new Random().nextInt(max - min + 1) + min;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private String getThreadName() {
        return "[" + Thread.currentThread().getName() + "] - ";
    }

}

Run the test case -

package com.amiyasahu;

public class App {
    public static void main(String[] args) {
        Thread t1 = new ThreadLocalTest();
        t1.start();
        
        Thread t2 = new ThreadLocalTest();
        t2.start();
        
        Thread t3 = new ThreadLocalTest();
        t3.start();
    }
}

Output -

[Thread-1] - com.amiyasahu.Singleton@7504f8eb
[Thread-2] - com.amiyasahu.Singleton@274b8c21
[Thread-0] - com.amiyasahu.Singleton@50dcdeae
[Thread-1] - com.amiyasahu.Singleton@7504f8eb
[Thread-1] - Both are equal
[Thread-0] - com.amiyasahu.Singleton@50dcdeae
[Thread-0] - Both are equal
[Thread-2] - com.amiyasahu.Singleton@274b8c21
[Thread-2] - Both are equal

This clearly shows, it is creating a unique instance per thread.

How to Make a dropdown readonly using Jquery

Dropdown (select element) is always read only. User do not edit it. User can select any of the option of its own chice. Unlike other html elements, it dont have a attribute which can make the element readony and prevent users to change its value.

So how do we do this, when we want to prevent the user not to edit its selected option.

There is a little trick. Why can’t we disable it.

Wait a second…

But as we are disabling this field, the field will not be the part of the request when the form is submitted.

We can do some work around for this.

So we need to use a hidden field to store disabled selected-option value. When the moment select element is disabled we need to create a hidden input field in the form and store the selected value. The moment it is enabled we need to restore the element with the value stored in the hidden field.

Here you go with a code example -

HTML code

<form action="#">
    <select id="choose" name="alpha">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
</form>

<button id="toggle">toggle enable/disable</button>

JQuery code

jQuery(document).ready(function($) {
    var $select = $('#choose'), 
    name = $select.prop('name'), 
    $form = $select.parent('form');

    //store the name in the data attribute 
    $select.data('original-name', name);  

    $('#toggle').on('click', function(event) {
        if($select.prop('disabled')){
            //enable the element
            //remove the hidden fields if any
            $form.find('input[type="hidden"][name='+name+']')
                 .remove(); 
            //restore the name and enable 
            $select.prop({ name : name, 
            		disabled : false}); 
        } else {
            //disable it 
            var $hiddenInput = $('<input/>', { type  : 'hidden',
                    	name  : name, 
                    	value : $select.val()
                    });

            //append the hidden field to the form
            $form.append( $hiddenInput );  
            //change name and disbale 
            $select.prop({ name : name + "_1", disabled : true });
        }
    });
});

Here is a live example.

How to count number of key/value pairs in JSON Object

To count the number key/value pairs in a JSON object we need to convert an array. And then we can easily count the number of element in the array which is same as the number key value pairs in the json object.

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found in the object.

function countObjectKeys(obj) { 
    return Object.keys(obj).length; 
}

//Usage 
var emp = {"firstName":"John", "lastName":"Doe"};
console.log(countObjectKeys(emp)); //2

Toggle Checkboxes using JQuery (Select All/Select None)

When user clicks Select All checkbox, the code first checks the status of checkbox with id select-all, and loops though each checkbox with class checkbox update their checked property to true. When it is clicked again then it will update their checked property to false.

1. HTML Code

<input type="checkbox" id="select-all"/> Select All
<input type="checkbox" class="checkbox" name="chk[]" value="1"> 1
<input type="checkbox" class="checkbox" name="chk[]" value="2"> 2
<input type="checkbox" class="checkbox" name="chk[]" value="3"> 3

2. JQuery code

$(document).ready(function() {
    $('#select-all').click(function(event) {
    	var btn = this, toStatus = btn.checked;
    	//loop through each checkbox
        $('.checkbox').each(function() { 
            $(this).prop('checked', toStatus);
        });
    });
});

Here is the live exaample

How to create nested HTML elements in JQuery

JQuery code

var $elem = $('body div.main');
$elem.append(
            $('<div/>', {'class': 'wrapper'}).append(
                $('<div/>', {'class': 'inner'}).append(
                    $('<span/>', {text: 'Some text'})
                )
            ).append(
                $('<div/>', {'class': 'inner'}).append(
                    $('<span/>', {text: 'Other text'})
                )
            )
        );

Result

<div class="main">
	<div class="wrapper">
		<div class="inner">
			<span>Some text</span>
		</div>
		<div class="inner">
			<span>Other text</span>
		</div>
	</div>
</div>

Here is a live example

Intresting Javascript tricks

Swap variables

var a = 10 , b = 20 ; 
console.log("a = " + a + " , b = " + b);  // a = 10 , b = 20
b = [a, a = b][0];                        // swap the variables 
console.log("a = " + a + " , b = " + b);  // a = 20 , b = 10

Truncate a value to a Integer in Javascript

Usage Result
~~0.125 0
~~1 1
~~1.6 1
~~"2.59" 2
~~-2.8 -2
~~"Apple" 0
~~[] 0
~~null 0

Note -: It never returns NaN. If it fails, it just returns 0

Check if given input is numeric in Javascript

function isNumeric (arg) {
    return !isNaN(parseFloat(arg)) && isFinite(arg);
}
Usage Result
isNumeric(10) true
isNumeric(10.234) true
isNumeric(0.215) true
isNumeric('10') true
isNumeric('10.234') true
isNumeric('0.215') true
isNumeric('') false
isNumeric('Qwerty') false
isNumeric('43Agd') false

Detect JQuery AJAX Requests with PHP

When you make a AJAX call to the server using JQuery, it adds a special header along with the request.

So you can check on the server side against this header.

If the header HTTP_X_REQUESTED_WITH is present and is equal to XMLHttpRequest, then the AJAX call is made via jQuery.

<?php
// returns true if the request is made with XMLHttpRequest header 
function isXhr() {
    return $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

// Usage 

if(isXhr()) {
    echo "The AJAX Request is made from JQuery ";
} else {
    echo "The AJAX Request might not be made from JQuery ";
}

How to delete a remote tag in git

If you need to delete a remote tag named – oldtag use the below command

git tag -d oldtag
git push origin :refs/tags/oldtag

How to check if an element exists in an array in Javascript

The below function can efficiently check whether an element exists in the array or not

if (!Array.prototype.elemetExists) {
    Array.prototype.elemetExists = function (string) {
        return !!~this.indexOf(string);
    };
}

//usage 
var fruits = ['Apple' , 'Banana' , 'Orange' , 'Mango'];
console.log(fruits.elemetExists('Banana'));  //true 
console.log(fruits.elemetExists('Lichi'));  //false