Tuesday, December 24, 2019

What is your first VS Code plugin?

Prettier enforces a consistent code style.



Other favourite plugins:

  1. Bracket Pair Colorizer
  2. Indent Rainbow
  3. Auto Rename Tag
What is your first VS Code plugin? Comment below.

Sunday, December 8, 2019

Quick Sort in Javascript

Quick sort is faster than bubble sort.

It uses the idea of divide and conquers. Divides the array into two halves using a pivot in such a way that elements in the left half are smaller than the pivot and elements in the right are greater than the pivot — then recursive using quick sort on the left and right parts.

I would recommend below youtube to understand Quick Sort:
https://www.youtube.com/watch?v=eqo2LxRADhU

Here is my implementation in javascript:
function quickSort(arr, start, end) {
  // Stop the recursion when the start equal or smaller to the end
  if (start >= end) { 
    return ; 
  };
  
  // Here is the magic happen
  let pivotIndex = partition(arr, start, end);
  
  // Recursion - quick sort the left part
  quickSort(arr, start, pivotIndex - 1);
  
  // Recursion - quick sort the right part
  quickSort(arr, pivotIndex + 1, end);
}

function partition (arr, start, end) {
  let pivotIndex = start; // Pivot location
  let pivotValue = arr[end]; // Use the last number  
  
  for (let i=start; i<end; i++) {
    // Move number that smaller than pivot value to the front.
    // Update pivot index
    if (arr[i] < pivotValue) {
      // Move to front
      swap(arr, i, pivotIndex);
      pivotIndex++;
    }
  }
  
  // Swap the pivot value to correct location
  swap(arr, end, pivotIndex);
  return pivotIndex;
}

function swap(arr, a, b) {
  let temp = arr[a];
  arr[a] = arr[b];
  arr[b] = temp;
}

let arr = [2 ,1, 4, 5, 3, 6, 6, 8, 1, 3];
quickSort(arr, 0, arr.length - 1);

Thursday, December 5, 2019

Bubble Sort in Javascript

Bubble soft is the most straightforward sorting algorithm that works by repeatedly swapping the elements if they are in wrong orders.

Example:

1. Swapping the first element.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

2. Swapping the second element.
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), No swap
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap

3. Pass the sorting criteris when there is no swapping.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap

Let write the code to do it:

let items = [1,2,3,5,4];

function bubbleSort(p_val){
  let sorted = p_val;
  
  for (let i=0, x=p_val.length; i<=x; i++){
      let isSwapRequired = false;
      for(let j=0; j<=x-i-1; j++){
        // compare items and only swap them if the second one's smaller
        if (sorted[j] > sorted[j+1]) {
          isSwapRequired = true;
          let first = sorted[j];
          let second = sorted[j+1];
          sorted[j+1] = first;
          sorted[j] = second
        }
    }
    // IF no two elements were swapped by inner loop, then break 
        if (!isSwapRequired) { break; };
  }
  
  return sorted;
}

document.write(bubbleSort(items));
The best case is when the array is already sorted, and worst case is the array is reverse sorted.

So that is the famous bubble sort. I will talk on other sorting algorithms next time.

Notes: There is a native javascript method to sort an array (Array.sort) that is more efficient and easier to use. This example is to demonstrate the bubble sort.

Wednesday, December 4, 2019

Recursion in Javascript

A recursive function is the ability to call itself and stop on matching the criteria.

For example, we could write a recursion to reverse a string from "ABC" to "CBA".

// Parameter: A string.
// Return: Last character of the string.

function reverseString(p_val){

  // Get the string's length
  var length = p_val.length;

  // Get the last character
  var lastchar = p_val.charAt(length - 1);

  if (length == 1) {

     // Return the last char
     return lastchar;

  } else {

    // Run the recursion
    return lastchar + reverseString(p_val.substring(0,length - 1))

  }

}

Let's say the parameter is "ABC". The process will be:
  1. Return: C + reverseString("AB") 
  2. Return: C + B + reverseString("A") 
  3. Return: C + B + A

Thursday, November 28, 2019

JavaScript: Define Multiple Instance in Module Pattern

In JavaScript: Module Pattern with Anonymous Closure article, I have shown you how to create a Module using Immediately-Invoked-Function-Expression (IIFE). With IIFE, you only can have a single instance of the object.

What if you need to have multiple instances? Example two armies carry different weapons.

Remove () in the ARMORY module in the previous Article.
var ARMORY = (function(){
  // Private
  var weaponList = [ * List of weapon object * ];
  var removeWeapon = function(...){};
  var replaceWeapon = function(...){};

  // Public
  return{
    makeArmorRequest: function(...){}
  }
});
Now you can create multiple instances:
var army1 = new ARMORY();
var army2 = new ARMORY();

Tuesday, October 29, 2019

If you are writing ES6 syntax in designer's script library, you will get an error - ""const is a reserve identified".









I think designer default to ES5 syntax checking.

To work around, you can write your javascript at "WebContent" folder using Package Explorer. For this example, I will put my javascript in "javascripts" folder.





















This is how you point the javascript:
  <script src"javascript/like_button.js"></script>

Reference:
https://hclpnpsupport.hcltech.com/csm?id=community_question&sys_id=3bc76f951bbc481877761fc58d4bcb5e

Thursday, October 24, 2019

Object Methods in Javascript

I have introduced "Merging Object via Object.assign()" in my previous article. In this article, I will go over other important build-in object methods.

Object.create()
Object.create() method is used to create a new object and link it to the prototype of an existing object.

Object.keys()
Object.keys() create an array containing the keys of an object.

Object.values()
Object.values() create an array containing the values of an object.

Object.entries()
Object.entries() creates a nested array of the key/value pairs of an object.

Object.assign() - I would like to mention again. :-)
Object.assign() is used to copy values from one object to another.

Object.freeze()
Object.freeze() prevents modification to properties and values of an object and prevents the property from being added or removed from an object.

Object.seal()
Object.seal() prevent new properties from being added to an object but allows the modification of existing properties.

Object.getPrototypeOf()
Object.getPrototypeOf() is used to get the internal hidden [[Prototype]] of an object, also accessible through the _proto_ property.

In this example, we can create an array and access to the Array prototype.
  const employees = ['Simon','Adam','John'];
  console.log(Object.getPrototypeOf(employees));
Output:












The output is showing the employee array has access to pop, find, and other array prototype methods.

This method can be useful to get information on the available prototype methods - String, Integer, and etc.

References: 
https://www.digitalocean.com/community/tutorials/how-to-use-object-methods-in-javascript