Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Javascript Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise’s then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.

As the then() and catch() methods return promises, they can be chained. The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.

<script>
    
let successAction = new Promise((resolve, reject) => {
    console.log('Initial');

    document.getElementById("promisePending").innerHTML = "Starting...";
    // do async action here.

    setTimeout( function() {
        let apiResponse = {};
        apiResponse.id = 1;
        apiResponse.name = "Folau";

        resolve(apiResponse);
        document.getElementById("promiseFullFilled").innerHTML = "fullfilled";

    }, 3000);

});

successAction.then((reponse) => {
    console.log(reponse);
    console.log('Do this');
})
.catch((error) => {
     // This is skiped because resolve is called above.
    console.error('Error');
    console.log(error);
}).finally(() => {
    console.log('finally!');
});

let failedAction = new Promise((resolve, reject) => {
    console.log('Initial');

    document.getElementById("promisePending").innerHTML = "Starting...";
    // do async action here.

    setTimeout( function() {
        let apiResponse = {};
        apiResponse.id = 1;
        apiResponse.name = "Folau";

        reject(apiResponse);
        document.getElementById("promiseRejected").innerHTML = "rejected";

    }, 3000);

});

failedAction.then((reponse) => {
    // This is skiped because reject is called above.
    console.log(reponse);
    console.log('Do this');
})
.catch((error) => {
    console.error('Error');
    console.log(error);
}).finally(() => {
    console.log('finally!');
});

</script>

 

Promise with API HTTP requests

<script>
    const axiosInstance = axios.create({
        baseURL: 'http://localhost:8888',
        timeout: 1000,
        headers: {
            "Content-type": "application/json",
            "token": "foobar"
        }
    });

    function getUser(){
        console.log("getUser");
        let headers = {
            "Content-Type": "application/json",
            "token":"lovemesomecoding-token"
        };

        let options = {};
        options.method = "GET";
        options.headers = headers;

        let id = 1;

        let url = "http://localhost:8888/users/"+id;

        let response = axiosInstance(url, options);

        response.then(response => {
            let data = response.data;
            let content = "";
            content += "id: "+data.id+"<br>";
            content += "firstName: "+data.firstName+"<br>";
            content += "lastName: "+data.lastName+"<br>";
            content += "email: "+data.email+"<br>";

            document.getElementById("getUserContent").innerHTML = content;

        }).catch(error => {
            console.log("error");
            let errorResponse = error.response.data;

            console.log(errorResponse);
            document.getElementById("errorMsg").innerHTML = errorResponse.message;

        });
    }

    function updateUser(){
        console.log("update user");
        let headers = {
            "Content-Type": "application/json",
            "token":"lovemesomecoding"
        };
        let user = {
            firstName: 'Folau',
            lastName: 'Kaveinga',
            email: 'folaukaveinga@gmail.com',
            id: 1
        };

        let options = {};
        options.method = "PUT";
        options.body = JSON.stringify(user);
        options.headers = headers;

        let url = "http://localhost:8888/users";

        let response = axiosInstance(url, options);

        response.then(response => {

            let data = response.data;

            let content = "";
            content += "id: "+data.id+"<br>";
            content += "firstName: "+data.firstName+"<br>";
            content += "lastName: "+data.lastName+"<br>";
            content += "email: "+data.email+"<br>";

            document.getElementById("updateUserContent").innerHTML = content;
            document.getElementById("errorMsg").innerHTML = "";

        }).catch(error => {
            console.log("error");
            let errorResponse = error.response.data;

            console.log(errorResponse);
            document.getElementById("errorMsg").innerHTML = errorResponse.message;

        });
        
    }
    
</script>

Asnyc/await

The async keyword before a function means that function always returns a promise. Other values are wrapped in a resolved promise automatically.

The await keyword makes JavaScript wait until that promise settles and returns its result.

<div class="row">
    <div class="col-1">

    </div>
    <div class="col-4">
        Get Average Number
        <br>
        <button onclick="getAverageNumber()" type="button" class="btn btn-outline-primary">Get It</button>
    </div>
    <div class="col-7" id="averageNum">
        
    </div>
</div>

<script>
    /*
    * Async and await
    */
    async function calculateAverage(num1, num2, num3){

        // This could be a REST API call
        let someNumber = await new Promise(resolve => {
            setTimeout(() => {
                resolve(3);
            }, 2000);
        });
        console.log("num1: "+num1 + ", num2: "+ num2 +", num3: "+ num3 + ", someNumber: "+someNumber);
        return (num1 + num2 + num3 + someNumber) / 4;
    }

    function getAverageNumber(){
        calculateAverage(2, 3, 4).then(average => {
            console.log("average");
            console.log(average);
            document.getElementById("averageNum").innerHTML = average;
        });
    }
</script>

 

Source code on Github

October 29, 2019

ArrayList

ArrayList is a resizable array or dynamic array implementation in java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object class. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is transient . It implements RandomAccess, Cloneable, java.io.Serializable.

Internally an ArrayList uses an Object[] Array which is an array of objects. All operation like deleting, adding and updating the elements happens in this Object[] array.  

ArrayList is one of the most used data structure in Java today.

ArrayList<String> fruits = new ArrayList<>(2);
fruits.add("apple");
fruits.add("banana");

// by adding this, the internal array is doubled it's size
fruits.add("cantalope");

System.out.println(fruits.toString());

Array is a fixed size data structure while ArrayList is not. Even if we specify some initial capacity, we can add more elements.

If we try to add an element using the add() method in the array list, Internally it checks for the capacity to store the new element, If the internal array is full then a new capacity(more than old capacity by 50% at least) is calculated and a new array is created and copied over the old array to it.

Performance of ArrayList       

The time complexity of the common operations in ArrayList java.

  • add(): For adding a single element O(1) . Adding n element in array list takes O(n).
  • add(index, element): adding element in particular index in average runs in O(n) time
  • get(): is always a constant time O(1) operation
  • remove(): runs in linear O(n) time. We have to iterate the entire array to find the element fit for removal
  • indexOf():  It runs over the whole array iterate through each and every element worst case will be the size of the array n .so, it requires O(n) time
  • contains(): implementation is based on indexOf(). So it will also run in O(n) time
  • The size, isEmpty, set, iterator, and listIterator operations run in constant time O(1)

 

Time Complexity

  • add() – takes O(1) time. However, worst-case scenario, when a new array has to be created and all the elements copied to it, is O(n).
  • add(index, element) – in average runs in O(n) time
  • get() – is always a constant time O(1) operation
  • remove() – runs in linear O(n) time. We have to iterate the entire array to find the element qualifying for removal
  • indexOf() – also runs in linear time. It iterates through the internal array and checking each element one by one. So the time complexity for this operation always requires O(n) time
  • contains() – implementation is based on indexOf(). So it will also run in O(n) time
October 22, 2019

Memory(Stack vs Heap)

What is RAM?

Computer random access memory (RAM) is one of the most important components in determining your system’s performance. RAM gives applications a place to store and access data on a short-term basis. It stores the information your computer is actively using so that it can be accessed quickly. 

The more programs your system is running, the more you’ll need RAM. The speed and performance of your system directly correlate to the amount of RAM you have installed. If your system has too little RAM, it can be slow and sluggish.

In this article, we are discussing Stack vs Heap which is that Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the RAM.

What is Memory?

Memory in a computer is just a sequential set of “buckets” that can contain numbers, characters, or boolean values. By using several buckets in a row, we get arrays. By giving names to a set of contiguous buckets, we get a “structure”. But at its core, a computer memory is a very simple list of numbers. Everything else must be built up upon this.

Memory Layout

  1. Memory is laid out in sequential order basically from 0 on up (one byte at a time). Each position in memory has a number (called its address!).
  2. The compiler (or interpreter) associates your variable names with memory addresses.
  3. In some languages like C, you can actually ask the computer for the address of a variable in memory. In C this is done using the ampersand &In many languages, the actual address is hidden from you and is of little use to you, as all the access methods “abstract” the details of the computer hardware away, allowing the programmer to concentrate on the algorithm, and not the details.
  4. Arrays variables simply contain the address of the first element of the array. Arrays are zero based so the address simply becomes the base address plus the index.
  5. Structure variables simply contain the address of the first element of the structure, and each “named” field of the structure forms an offset from the first bucket. The computer keeps track of this offset so that the programmer can use symbolic names instead of numbers.
  6. Memory buckets are 8 bits long (or one byte). A character (char) is one byte. An integer is (usually) four bytes. A float is four bytes. A double is 8 bytes.

What is a Stack?

A stack is a special area of computer’s memory which stores temporary variables created by a function. In stack, variables are declared, stored and initialized during runtime.

It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased. The stack section mostly contains methods, local variable, and reference variables.

The stack is a LIFO (Last-In-First-Out) data structure. You can view it as a box of perfectly fitted books — the last book you place is the first one you take out. By using this structure, the program can easily manage all its operations and scopes by using two simple operations: push and pop.

These two do exactly the opposite of each other. Push inserts the value to the top of the stack. Pop takes the top value from it.

To keep track of the current memory place, there is a special processor register called Stack Pointer. Every time you need to save something — like a variable or the return address from a function — it pushes and moves the stack pointer up. Every time you exit from a function, it pops everything from the stack pointer until the saved return address from the function. It’s simple!

What is a Heap?

The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space. It supports Dynamic memory allocation.

Heap is created when the JVM starts up and used by the application as long as the application runs. It stores objects and JRE classes. Whenever we create objects it occupies space in the heap memory while the reference of that object creates in the stack. It does not follow any order like the stack. It dynamically handles the memory blocks. It means, we need not to handle the memory manually.

For managing the memory automatically, Java provides the garbage collector that deletes the objects which are no longer being used. Memory allocated to heap lives until any one event, either program terminated or memory free does not occur. The elements are globally accessible in the application. It is a common memory space shared with all the threads. If the heap space is full, it throws the java.lang.OutOfMemoryError

Differences between Stack and Heap

Parameter Stack Memory Heap Space
Application It stores items that have a very short life such as methods, variables, and reference variables of the objects. It stores objects and Java Runtime Environment (JRE) classes.
Ordering It follows the LIFO order. It does not follow any order because it is a dynamic memory allocation and does not have any fixed pattern for allocation and deallocation of memory blocks.
Flexibility It is not flexible because we cannot alter the allocated memory. It is flexible because we can alter the allocated memory.
Efficiency It has faster access, allocation, and deallocation. It has slower access, allocation, and deallocation.
Memory Size It is smaller in size. It is larger in size.
Java Options Used We can increase the stack size by using the JVM option -Xss. We can increase or decrease the heap memory size by using the –Xmx and -Xms JVM options.
Visibility or Scope The variables are visible only to the owner thread. It is visible to all threads.
Generation of Space When a thread is created, the operating system automatically allocates the stack. To create the heap space for the application, the language first calls the operating system at run time.
Distribution Separate stack is created for each object. It is shared among all the threads.
Exception Throws JVM throws the java.lang.StackOverFlowError if the stack size is greater than the limit. To avoid this error, increase the stack size. JVM throws the java.lang.OutOfMemoryError if the JVM is unable to create a new native method.
Allocation/ Deallocation It is done automatically by the compiler. It is done manually by the programmer.
Cost Its cost is less. Its cost is more in comparison to stack.
Implementation Its implementation is hard. Its implementation is easy.
Order of allocation Memory allocation is continuous. Memory allocated in random order.
Thread-Safety It is thread-safe because each thread has its own stack. It is not thread-safe, so properly synchronization of code is required.

 

October 21, 2019

Array

Array is a data structure that holds a fixed number of values (data points) of the same data type. Each item, or value, is called an element. When we initialize an array, we get to choose what type of data(data type) it can hold and how many elements(length) it can hold. 

Each position in the array has an index, starting at 0.

The items in an array are allocated at adjacent(next to each other) memory locations. 

By default, an array are filled with default value of its data type once it’s initialized. For example an array of int will have 0 as the default value.

From the above image:

  • data type – integer
  • length – 6
  • array name – Arr
  • first index – 25
  • last index – 7
int[] arr = new int[6];
arr[0] = 25;
arr[1] = 35;
arr[2] = 45;
arr[3] = 53;
arr[4] = 25;
arr[5] = 7;

System.out.println("length: " + arr.length);

System.out.println(Arrays.toString(arr));

arr = new int[]{25, 35, 45, 53, 25, 7};

System.out.println("length: " + arr.length);

System.out.println(Arrays.toString(arr));
length: 6
[25, 35, 45, 53, 25, 7]
length: 6
[25, 35, 45, 53, 25, 7]

 

Worst Case(Big O)

space
lookup
append(last element)
insert
delete

Advantages

  • Fast lookups – retrieving an element at a given index takes  time, regardless of the length of the array.
  • Fast appends – adding a new element at the end of the array takes  time, if the array has space.
  • An array can store multiple values in a single variable.
  • Arrays are fast as compared to primitive data types.
  • We can store objects in an array.
  • Members of the array are stored in consecutive memory locations.

Disadvantages

  • Fixed size. You need to specify how many elements you’re going to store in your array ahead of time. (Unless you’re using a fancy dynamic array.)
  • Costly inserts and deletes. You have to “scoot over” the other elements to fill in or close gaps , which takes worst-case  time.
  • We cannot increase or decrease the size of the array at runtime.
  • In array, memory wastage can be more.
  • We can only store similar data type items.

Inserting elements into an Array

If we want to insert something into an array, first we have to make space by “scooting over” everything starting at the index we’re inserting into.

In the worst case we’re inserting into the 0th index in the array (prepending), so we have to “scoot over” everything in the array. That’s  time.

In java

If we want to insert something into an array, first we must have the index or position where the element is going to. Once we have the position, we just set it.

In the worst case the time complexity is  time.

 

Deleting elements from an Array

Array elements are stored adjacent to each other. So when we remove an element, we have to fill in the gap—”scooting over” all the elements that were after it.

In the worst case we’re deleting the 0th item in the array, so we have to “scoot over” everything else in the array. That’s O(n) time.

Why not just leave the gap? Because the quick lookup power of arrays depends on everything being sequential and uninterrupted. This lets us predict exactly how far from the start of the array the 138th or 9,203rd item is. If there are gaps, we can no longer predict exactly where each array item will be.

In java

If we want to delete an element from an array, first we must have the index or position where the element is in. Once we have the position, we just set it to its data type default value, 0 or null. FYI, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements

In the worst case the time complexity is  time.

 

October 20, 2019

Git Pull Request

A pull request is a request asking your upstream project to pull changes into their tree. The request, printed to the standard output, begins with the branch description, summarizes the changes and indicates from where they can be pulled.

The upstream project is expected to have the commit named by <start> and the output asks it to integrate the changes you made since that commit, up to the commit named by <end>, by visiting the repository named by <url>.

git request-pull [-p] <start> <url> [<end>]

 

October 19, 2019