Saturday, April 11, 2020

Getter and Setter in JS

Let us suppose we have an object called User like this:
1
2
3
4
const user = {
    firstName: 'A',
    lastName: 'B',
}

Now suppose we want to return the full name of the function it will something be like this:

1
console.log(`${user.firstName} ${user.lastName}`)

But this is a naive approach and in case if we have to add something extra in the statement, we have to change every where, instead the better way is to give a function that will return this expression/value like:

1
2
3
4
5
6
7
8
9
const user = {
    firstName: 'A',
    lastName: 'B', 
    fullName () { // previous version was like fullName: function () {...} but changed in ES6
        return `${this.firstName} ${this.lastName}`
    }
}

console.log(${user.fullName())

Now this is good but:
  1. what if you want to use it as a field and not as a function, I mean, I want to use it something like: console.log(${user.fullName).
  2. And we want to set the value of firstName and lastName on the basis of value we are going to pass to fullName like user.fullName = 'Javascript rocks' 
For that we have 2 keywords called get and set and the use is like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const user = {
    firstName: 'A',
    lastName: 'B', 
    get fullName () {
        return `${this.firstName} ${this.lastName}`
    }

    set fullName (value) {
        const tokens = value.split(' ');
        this.firstName = tokens[0];
        this.lastName = tokens[1];
    }
}

console.log('Before set', ${user.fullName})

user.fullName = 'Javascript Rocks'.

console.log('After set', ${user.fullName})

Here in this code there are 2 keywords we have seen,

  • get = for accessing the property (at line 4)
  • set = for setting the property (at line 8)
These 2 keywords make the function as a property and that is the reason at line 15 and line 19 we have accessed the fullName without the parenthesis.

That's it, its awesome right :)

Happy Coding :)

For reference, please check out this: https://www.youtube.com/watch?v=bl98dm7vJt0

Thursday, April 9, 2020

debouncing in javascript

So, we have seen the requirements where in which we are required to send the data to the server on an event that might be a click, hover, mouseEnter or anything.

So let us consider we are writing a click event for a button. So the basic code for the same would look something like this:

1
2
3
4
5
$(document).ready(() => {
    $("#btn").on('click', async (event) => {
        // do some api calls or anything
    })
})

Now suppose you are saving/posting the data to the server on every click, in that case if suppose, user clicked the button 2 3 times, it will save the same data 3 times with different ids.

In order to handle this we have 2 options:
  1. either disables the button once you click and enables it once the callback returns
  2. Write a debounce function to handle accidental clicks
Lets see first how debounce function is written.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const debounce = (fn, delay) => {
    let timeoutId;
    return (...args) => {
        if(timeoutId) clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn(...args),delay)
    }
}

$(document).on('ready', async() => {
    $('#btn').on('click', debounce(e=> {
        console.log('bye bye')
    }, 2000))
})

Explanation:
  1. In this code, we have first created a higher order function named debounce that is taking 2 params, the callback function and a delay to reset the functionality if, someone triggered the event twice.
  2. The debounce function is returning a function that is calling our callback passed at line 5.
  3. Now, instead of giving the callback directly to the event, we are calling debounce and passing our callback function implementation as well as the delay that is going to wait for certain time, before resetting the timeout.
That's it, this debounce function is a nice way of making sure that the accidental triggering of the events can be stopped and only the last event will be considered. This makes sure that all the events that are triggered before the timeout mentioned are going to keep on cancelling unless user stops the event creation and only the last triggered event is accepted and fires the actual callback.

Happy Coding :)

Thursday, January 16, 2020

forEach, map, filter, find, every, some, reduce in pure js implementation

These are normal functions but can be implemented with Array.prototype as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// ForEach loop
const myForEach = (array, cb) => {
  for (let i = 0; i < array.length; i++) {
    cb(array[i], i, array)
  }
}

// map function
const myMap = (array, cb) => {
  const result = []
  for (let i = 0; i < array.length; i++) {
    result.push(cb(array[i], i, array))
  }
  return result
}

// Find first element if predicate is passed
const myFilter = (array, cb) => {
  const result = []
  for (let i = 0; i < array.length; i++) {
    if (cb(array[i], i, array)) {
      result.push(array[i])
    }
  }
  return result
}

// Find first element if predicate is passed
const myFind = (array, cb) => {
  for (let i = 0; i < array.length; i++) {
    if (cb(array[i], i, array)) {
      return array[i]
    }
  }
  return null
}

// If all of the elemnts pass the predicate
const myEvery = (array, cb) => {
  for (let i = 0; i < array.length; i++) {
    if (!cb(array[i], i, array)) {
      return false
    }
  }
  return true
}

// If some of the elemnts pass the predicate
const mySome = (array, cb) => {
  for (let i = 0; i < array.length; i++) {
    if (cb(array[i], i, array)) {
      return true
    }
  }
  return false
}
const myReduce = (array, callback, initialVal) => {
  for (let i = 0; i < array.length; i++) {
    initialVal = initialVal ? callback(initialVal, array[i], i, array) : array[i]
  }
  return initialVal
}

// TESTING
const aa = [1, 2, 3]

console.log('===== MY FOREACH ======')
myForEach(aa, a => console.log(a))

console.log('\n\n===== MY MAP ======')
const retOfMyMap = myMap(aa, a => a * 2)
myForEach(retOfMyMap, a => console.log(a))

console.log('\n\n===== MY FILTER ======')
const retOfMyFilter = myFilter(aa, a => a % 2 === 1)
myForEach(retOfMyFilter, a => console.log(a))

console.log('\n\n===== MY FIND ======')
const retOfMyFind = myFind(aa, a => a > 1)
console.log(retOfMyFind)

console.log('\n\n===== MY EVERY ======')
const retOfMyEvery = myEvery(aa, a => a > 0)
console.log(retOfMyEvery)

console.log('\n\n===== MY SOME ======')
const retOfMySome = mySome(aa, a => a > 10)
console.log(retOfMySome)

console.log('\n\n===== MY REDUCE ======')
const retOfMyReduce = myReduce(aa, (a, b) => a * b)
console.log(retOfMyReduce)


Since these are normal functions that is why we have taken the reference of array as a part of functional parameters, but when we make the functions as a part of array prototype then all references of 'array' can be changed to this., like:

1
2
3
4
5
Array.prototype.myForEach = function(cb) {
  for (let i = 0; i < this.length; i++) {
    cb(this[i], i, this)
  }
}

NOTE: Here in this function we did not use the arrow functions, the reason is simple, if we use the arrow functions the lexical scope of the function will be the function itself and not around the array value that called the function, and that is the reason we placed the normal function instead of arrow functions.
You can take more info from: https://stackoverflow.com/questions/36225636/function-to-array-prototype

Happy coding
:)

Starting the live server of VSCode in SSL/Https Mode

Hi we all need a server many times in our development setup to host our files and work on it. For this, one way is to always add the server code and respond html files and js files without processing (if its a normal html project).

But we have a better option like live server plugin, that supports hot reloading as well, that means as soon as you change any files on your coding it will reload the browser window as well.

Live server plugin of VSCode exactly gives the support where in which, if you write some html file and you want to host it on the server you can use this plugin for starting the server for your coding folder.

Prerequisites:
  1. VScode
  2. Install Live server Plugin in VScode from: https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
  3. You can read the documentation, what is supports and what are its shortcuts.
The main problem is that sometimes we need to start the server in the https mode that is ssl mode, at that time we have to do certain config changes in order to start the live server in ssl mode. So here are the steps:
  1. We have to generate the key-pem file pair for starting the server in https mode.
  2. For that we first use following commands:
    1. Create a private key :
      openssl genrsa -aes256 -out localhost.key 2048
      For this we have to provide a password.
    2. Create the certificate:
      openssl req -days 3650 -new -newkey rsa:2048 -key localhost.key -x509 -out localhost.pem
      Give the details and provide password (from step 1) for generating the certificate
    3. Create a .vscode folder in root of your project and create settings.json file inside of it
    4. Add the following code in that:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "liveServer.settings.port": 5501,
  "liveServer.settings.root": "/",
  "liveServer.settings.CustomBrowser": "chrome",
  "liveServer.settings.https": {
    "enable": true,
    "cert": "PATH TO FOLDER/localhost.pem",
    "key": "PATH TO FOLDER/localhost.key",
    "passphrase": "PASSWORD OF STEP 1"
  }
}

Now if you start the live server by pressing Go Live button you server will be started in SSL mode and chrome will prompt you to verify the ssl website, since you are in local, just click advanced and proceed anyway, and boom your server is in ssl mode.

Here are the references I took help from:
  1. https://gist.github.com/prof3ssorSt3v3/edb2632a362b3731274cfab84e9973f9
  2. https://www.youtube.com/watch?time_continue=144&v=v4jgr0ppw8Q&feature=emb_logo
Here is the dummy code to check for starting the server in SSL mode https://github.com/ankur20us/demo-live-server-ssl

Happy Coding
:)