Java – Storing Integer Value of Bit-Mask

In this tutorial, we will guide you how to show an integer’s 1s position on bit level.

Example:

26 => {1, 3, 4}

Use java.util.BitSet to store, well, a set of bits.

Util.java
package com.cloudberry.com.my;
import java.util.BitSet;

public class Util{
    public static BitSet fromInt(int num) {
        BitSet bs = new BitSet();
        for (int k = 0; k < Integer.SIZE; k++) {
            if (((num >> k) & 1) == 1) {
                bs.set(k);
            }
        }
        return bs;
    }

    public static int toInt(BitSet bs) {
        int num = 0;
        for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) {
             num |= (1 << k);
        }
        return num;
    }
}

The above utilities method in Util.java will be consumed in Main class.

Main.java
package com.cloudberry.com.my;

import static com.cloudberry.com.my.Util.fromInt;
import static com.cloudberry.com.my.Util.toInt;

import java.util.BitSet;
public class Main {
	public static void main(String args[]) {
		try {
			int num 		= 0b11010; //Which is 26 in decimal
			BitSet result 	= fromInt(num); 
			System.out.println("fromInt() is called => " + result); //Display which position from left to right, is flagged as 1s.
			System.out.println("toInt() is called => " +  toInt(result));
		}
		catch(IndexOutOfBoundsException ibex) {
			System.out.println(ibex.getMessage());
		}
	}
}
Output:
fromInt() is called => {1, 3, 4}
toInt() is called => 26

References

Static Import
BitSet

JavaScript – How to get response from an asynchronous call

Promise in JavaScript is very handy for asynchronous task such as fetching a URL.
Developers who use Promise a lot, often will have to call then() with 1 callback function in it.

promise.then((result) => {});

promise.then(function(result){});

Prior to Promise, developers tend to use callback functions to handle asynchronous call in JavaScript. However, callback functions have potential problem which might lead to an anti pattern known as Callback Hell.

Callback hell is an anti-pattern which consists of multi-nested callback functions. With Promise callback hell can be prevented.

In ES2016, there are these async and await expressions which make Promise based codes look even better in readability. In addition to this, by using async and await, they make codes look as if running in procedural way. Developers do not have to use then() to process the result returned by Promise anymore.

Fetching Data using Promise

promise.js
(() => {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => response.text())
    .then((text) => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
})();

The above code snippets demonstrates Promise full-fills network request with Fetch API.

Async and Await

asyncawait.js
(async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    console.log(await response.text());
  }
  catch (err) {
    console.log('fetch failed', err);
  }
})();

The above code snippets demonstrates how async and await full-fills network request. It does exactly the same thing as in promise.js using async and await keywords

To create an async function, a function has async keyword before it. Also await keywords are only valid in async functions. If there is value return from an async function, it will always be a Promise.

References

Async Expression
Fetch API

JavaScript – Create Dynamic JavaScript Functions through Function Constructor

A JavaScript function can be created with Function constructor like followings:

// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function('a', 'b', 'return a + b');

// Call the function
adder(5, 3);
// > 8

In the above example adder is now a function. However there are 2 points I would like to highlight.

1. Calling the constructor directly can create functions dynamically, but suffers from security and performance issues similar to eval.

2. JavaScript functions created with Function constructor is always in global scope.
When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called.

var x = 10;

function createFunctionOne() {
    var x = 20;
    return new Function('return x;'); // this |x| refers global |x|
}

function createFunctionTwo() {
    var x = 20;
    function f() {
        return x; // this |x| refers local |x| above
    }
    return f;
}

var f1 = createFunctionOne();
console.log(f1());          // 10
var f2 = createFunctionTwo();
console.log(f2());          // 20

Git – Untrack files already added to git repository based on .gitignore

It happened that an IDE specific file or folder is tracked and push to remote repository without intention.

1. To remove an IDE specific track file or directory. First change directory to the path where the file or directory is located.

Then run the following command:
git rm --cached FILENAME

or

git rm -r --cached FOLDERNAME/

2. Add the FOLDERNAME/ or FILENAME within .gitignore.

3. Stage all files. git add .

4. Commit git commit -m "Remove IDE specific files".

5. Then do a git push to if you want to reflect the changes in remote repository.

JavaScript – How to remove a particular element from an array

To remove an element from an array. First, we need to find the index of the element you wish to remove.

var array = [100, 200, 300];
var index = array.indexOf(300);

if (index > -1) {
    array.splice(index, 1);
}

console.log(array);

Then remove it with splice()

Output

(2) [100, 200]

JavaScript – How to get current Date

To get current date. Use new Date() to generate a new Date object containing the current date and time.

var today   = new Date();
var dd       = today.getDate();
var mm       = today.getMonth()+1; //January is 0!
var yyyy     = today.getFullYear();

if(dd < 10) {
    dd = '0'+dd
} 

if(mm < 10) {
    mm = '0'+mm
} 

today = dd+ '/' + mm + '/' + yyyy;
console.log(today);

This will give you today’s date in the format of dd/mm/yyyy. Simply change today = dd+'/'+ mm+'/'+ yyyy; to whatever format you wish.

JavaScript – How do I loop through an object

Given an object as following:

var o = {
    "k1": "value1",
    "k2": "value2",
    "k3": "value3"
};

To loop through it, then do following:

for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key + " - " + JSON.stringify(o[key]));
    }
}
Output
k1 - "value1"
k2 - "value2"
k3 - "value3"

References:
MDN Web Docs -Object.prototype.hasOwnProperty()