Method Chaining in TypeScript

In this post, we’re going to implement method chaining pattern using TypeScript.

What is method chaining?

Method chaining is a pattern which allows the developers to invoke multiple methods on the same instance of object. When used efficiently, this pattern makes the code a lot more readable.

If you write JavaScript for living, chances are you’ve already used method chaining in one way or another.

Here’s an example of method chaining in jQuery.

$("#card")
  .css('background', 'red')
  .width(400)
  .text('hello world!');

Implementing method chaining

Let’s start by building a Calculator class

class Calculator {
    private _value: number;
 
    constructor(value: number) {
        this._value = value;
    }
 
    add(num: number): Calculator {
        this._value = this._value + num;
        return this; 
    }
    subtract(num: number): Calculator {
        this._value = this._value - num;
        return this;
    }
    multiply(num: number): Calculator {
        this._value = this._value * num;
        return this;
    }
    divide(num: number): Calculator {
        this._value = this._value / num;
        return this;
    }
    result(): number {
        return this._value;
    }
}

As you can see, each method on the class returns this i.e the current instance of the object.

Now, lets create an object using out Calculator class and call it’s methods.

const calc = new Calculator(10);
console.log(
    calc.add(10)
        .multiply(5)
        .divide(10)
        .subtract(4)
        .result()
);

The above code will output 6 in the console.

That’s it! I hope you liked this post. If you’ve any query or feedback, feel free to drop a comment.

Set default node version with NVM

NVM or the Node version manager is a tiny command line application which enables you to efficiently manage multiple versions of node on your computer.

In this quick post, we’ll learn to set the default version of node using NVM.

To set the default node version use the following command. Make sure you replace 10.15.0 with your desired version.

nvm alias default 10.15.0

If you encounter an error similar to something as shown below, the version you’re trying to use might not be installed on your computer.

! WARNING: Version '10.15.0' does not exist.
default -> 10.15.0 (-> N/A)

Use the following command to install the missing node version and then try to set it as the default version.

nvm install 10.15.0

To make sure if NVM has set the desired node version as default use the following command.

node -v

If everything went well you’ll see the following output in your terminal window.

v10.15.0

Must Read: LocalStorage in JavaScript

Custom Pipes – Angular

Pipes are used for transforming or formatting your data from within your templates. Angular comes bundled with a large number of built-in pipes including uppercase, lowercase, date, currency, and percent. However, there is a good chance that you might run into scenarios where you’ll need to create your own custom pipes.

In this post, we’re going to create our own custom pipe. We’re going to build pipe which accepts a number and returns it’s square. We’ll start by creating a new Typescript file ‘square.pipe.ts’.

Next thing we’ll do is import Pipe decorator and PipeTransform interface at the top of that file.

import { Pipe, PipeTransform } from '@angular/core';

Next, we’ll create a class SquarePipe which implements the PipeTransform interface and we’ll decorate it with Pipe decorator.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'square'
})
export class SquarePipe implements PipeTransform {
 
}

The value of name property is used to refer to the pipe inside the template.

Now, we’ll create a method called transform which accepts the value that needs to be processed and returns it’s square.

transform (value: number): number {
    if (isNaN(value)) {
      return value;
    }

    return value * value;
  }

The if condition determines if the value to be processed is a number. If not we’ll return the original value.

The final code is as follows:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'square'
})
export class SquarePipe implements PipeTransform {
  transform (value: number): number {
    if (isNaN(value)) {
      return value;
    }

    return value * value;
  }
}

Before using the pipe, we need to make our Angular app aware of the pipe. We can do that by adding pipe to our declarations array in the module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SquarePipe } from './square.pipe';

@NgModule({
  declarations: [
    AppComponent,
    SquarePipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

You can use our custom pipe in following way.

{{ num | square }}

Passing arguments to the pipe

You can also pass parameters to your pipe. For example, we’re passing city name as parameter to greeter pipe.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'greeter'
})
export class GreeterPipe implements PipeTransform {
  transform (value: string, city: string): string {

    return `Hello ${value}! Welcome to ${city}.`
  }
}

You can use the above pipe in following way.

{{ 'John' | greeter : 'Pune' }}

The above code will produce following output.

Hello John! Welcome to Pune.

I hope you found this post about Angular Pipes useful. If you have any query or feedback feel free to drop a comment.

Useful Read: Inject Document In Angular

LocalStorage in JavaScript

LocalStorage is a part of Web Storage API which allows the developers to store data on the user’s web browser in stringified JSON format. The data stored in LocalStorage is persisted even after the web browser is closed and doesn’t have an expiration date. The data is stored in LocalStorage in key/value pairs.

LocalStorage API provides 5 methods to interact with Storage.

1. setItem

As the name suggests, it allows the users to add new values to the storage. This method accepts two parameters, the first parameter is the key which used to identify the data and second is the value needs to be stored.

localStorage.setItem('nameOfclient', 'Sam');

In the above example nameOfclient is the key and Sam is the value to be stored.

2. getItem

The getItem method is used to retrieve the values stored in localStorage. It accepts only one parameter the key and returns the value as a string.

const clientName = localStorage.getItem('nameOfclient');

In the above example, we’re using nameOfClient as key which points to value Sam.

3. removeItem

This method deletes the key / value pair from the localStorage. It accepts only one parameter the key of item that needs to be deleted.

localStorage.removeItem('nameOfclient');

4. clear

The clear method deletes all the records stored in the localStorage. It does not accept any parameters.

localStorage.clear();

5. key

This method will accept the index number of the item inside localStorage and will return key name of that item.

const firstKeyName = localStorage.key(0);

Storing objects and arrays inside LocalStorage

LocalStorage can only store strings. If you wish to store arrays or objects within the localStorage you first need to convert it to string. This can be easily done using JSON.stringify method. Consider the following example.

const person1 = {
  name: 'Sam',
  city: 'New York',
}
localStorage.setItem('person1', JSON.stringify(person1));

As you can see, we’re first converting the person1 object to string and then passing it to the setItem method.

To retrieve the stringified data we need to first parse it using JSON.parse method.

let person1 = JSON.parse(localStorage.getItem('person1'));

Checking for items in localStorage

In order to verify if there are any items in localStorage you can use the following code.

if (localStorage.length > 0) {
  // You've items in you're localStorage
} else {
  // You don't have anything in you're localStorage
}

Looping over items in LocalStorage

You can use localStorage.length property to loop over items stored in localStorage.

for ( var i = 0; i < localStorage.length; i++ ){
  console.log(localStorage.getItem(localStorage.key(i))) 
}

Must Read: How To Get Current Date In JavaScript

Thank you for reading. I hope you found the post helpful. In case you’ve any queries or feedback feel free to drop a comment in the comment section.

How to Use Shortcodes in Your WordPress Sidebar Widgets

WordPress out of the box doesn’t allow you to add shortcodes to the Text widget within the sidebar. However, there is a easy workaround for this issue.

All you need to do is add the following code to your functions.php file.

add_filter('widget_text', 'do_shortcode');

The above code will parse the content of text widget and execute shortcodes before loading the widget.

Must Read: How to inject Document in Angular service

JavaScript Ternary Operator

If statement in JavaScript provides you a way to execute a block of code conditionally.

const age = 19
if (age >= 18) {
    console.log('you are old enough to drive');
} else {
    console.log('you are too young to drive');
}

However, there is a shorter way accomplish this:

const age = 19;
age >= 18 ? console.log('you are old enough to drive') : console.log('you are too young to drive');

Syntax

condition ? expression one : expression two;

As you can see in the syntax the ternary operator consists of the condition followed by two expressions. If the condition results to true, expression one is executed else expression two is executed.

Ternary operator is primarily used to conditionally assign values to the variables.

const age = 19;
const canDrive = age >= 18 ? true : false;
console.log(canDrive); // true

Recommended: How to get current date in JavaScript?

How To Get Current Date In JavaScript

In this short post, we’re going to understand how we can get current date in JavaScript.

The following code will log the current date in the console in mm/dd/yyyy format.

const now = new Date();
let day = now.getDate();
let month = now.getMonth() + 1;
let year = now.getFullYear();

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

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

const today = month + '/' + day + '/' + year;
console.log(today);

Now, let’s go line by line and understand what exactly is happening in this code.

const now = new Date();
let day = now.getDate()();
let month = now.getMonth() + 1;
let year = now.getFullYear();

At line one, we’re creating a new instance of the date object. And in the next three lines, we’re extracting the day, month and year.

  • getDate – returns the current date (1-31).
  • getMonth – returns the current month (0-11). Values start at zero that represents January and ends at eleven that represents December. Hence we’re adding one to month.
  • getFullYear – returns current year in four digit format e.g. 2019.
if(day < 10) {
    day = '0' + day
} 

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

Next, we’re adding zero at the beginning of day and month if they are single digit numbers.

const today = month + '/' + day + '/' + year;
console.log(today);

And at the last two lines we’re simply concatenating the day, month and year in mm/dd/yyyy format and logging it to the console.

Must Read: JavaScript ES6 – What are Template Literals

Thank you for reading. I hope you found this post useful. In case you’ve any query or feedback feel free to drop a comment on this post.

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

JavaScript ES6 – What are Template Literals

Since the beginning of time JavaScript developers are using single quotes and double quotes to create strings. However, ES6 specification came with template literals which is more elegant way of creating strings. In this post, we’re going to understand what template literals are? And how to use them within your applications to improve code readability?

Basic Usage:

We usually use single or double quotes to create strings.

const name1 = 'sam';
const name2 = "harry";

When it comes to template literals we need to use the back tick key located on the upper let corner of your keyboard. A basic example of template literals is as follows.

const name3 = `john`;

Line Breaks:

Before ES6, we had to use \n to maintain line breaks between our strings. The following code will log the string in 2 lines.

const myText = 'I am on line one. \n I am on line two';
console.log(myText);

We can do the same using template literals in much a simpler way.

const myText = `I am on line one.
I am on line two.`;
console.log(myText);

Note that template literals are space sensitive.

const myText = `I am on line one.
                I am on line two.`;
console.log(myText);

The above code will produce the following output in the console.

I am on line one.
                I am on line two.

Interpolation:

In order to interpolate variables in variables or expression in traditional strings, you would use following syntax:

const num = 2;
console.log('Square of ' + num + ' is ' + (num * num));

You can do the same thing in much simpler way using template literals.

const num = 2;
console.log(`Square of ${num} is ${num * num}`);

As you can see in the above code, you can simply add your variables or expressions to dollar sign followed by curly braces in order to interpolate them.

Recommended: How To Inject Document Object In Angular Service

I hope you found this post useful. In case if you’ve any query or feedback feel free to drop a comment.

How To Inject Document Object In Angular Service

In this short post, we’re going to understand how we can inject document object within an Angular service.

Angular comes bundled with a DI token that refers to the document object. We can use the @Inject decorator to inject this token within our service or component.

import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable()
export class MyCustomService {
  constructor(@Inject(DOCUMENT) private document: Document) {
  
  }
}

Must Read: Var, let and const- what’s the difference?

10 Hilarious CSS Puns That’ll Make You Laugh

Our jobs as web developers are quite frustrating, hence it’s sometimes a good thing to have a little fun at the office. Here’s a list of CSS puns you’ll find hilarious which I found on this reddit thread.

1. Boo!

.ghost

2. You don’t simply see the ninja, the ninja sees you!

.ninja

3. Titanic?

.titanic

4. The Lego blocks

.lego

5. Kim’s secret

#kim-kardashian

6. Wife is always right!

#wife

7. IKEA tables are best!

#ikea

8. One does not simply, join Illuminati.

#illuminati

9. Tower of Pisa.

#tower-of-pisa

10. Eminem!

#eminem

My favourites are 1, 2 and 10. What about you?

Must Read: JavaScript — Double Equals vs. Triple Equals