Categories
interview

Javascript call() vs apply() vs bind()

call

The call() is a predefined Javascript function which can used to call a method of an object while passing it another object. For example, if you look at the following code, you will observe that the object being passed into the call() method replaces the this variable of the object whose method is being invoked.

Categories
Uncategorized

Testing Component with Service (Promise) in Angular

To perform unit testing on a component that makes use of a service, that returns a promise, we can use fakeAsync() and spy() methods from Angular’s unit testing package.

Categories
interview

Passing an object vs primitive data type in Js

In Javascript, when you pass a primitive data type like String or Int in Java to a function or a method, and a function modifies it, then this does not effect the actual data being passed. For example,

Categories
interview

Floyd Warshall Algorithm

The Floyd Warshall Algorithm is used to find the shortest distance between all pairs in a weighted graph with positive or negative edges. It makes use of Dynamic Programming.

  • If A, B, C are vertices, then this algorithm checks for the following
    if (AC > AB + BC)
    AC  = AB + BC;
Categories
interview

Kth largest element in an Array

Kth largest element in an array can be determined using the “Quickselect Algorithm”.

Average performance O(n)
Worst-case performance O(n^2)

Categories
Uncategorized

Interview Structure for Top Tech Companies

Amazon

Usually for SDE I, the interview involves

  • 1 Phone screen with coding.

    Onsite
  • 3 Onsite whiteboard coding interviews (includes bar raiser)
  • 1 System Design round
  • 1 Behavioral round

Google

For entry level software engineers, usually it comprises of

  • 1 Hangouts coding session

    Onsite
  • 5 whiteboard onsite coding interviews

Microsoft

For different levels of Software Engineering positions, usually the interview comprises of

  • 1 Skype coding session

    Onsite
  • 5 whiteboard onsite coding interviews

Most tech companies try to test your ability to apply core Computer Science fundamentals to solve problems.

Categories
Uncategorized

What is Dynamic Programming?

Dynamic Programming is a way of solving a problem by breaking it down into smaller sub problems and storing them without having to recalculate them. Usually this involves 3 main methods.

Categories
Uncategorized

Flashing your Samsung Galaxy S7 Edge (T-Mobile)

You will need a Windows PC for this. Make sure you have backed up your data before proceeding.

  • Download the Samsung Android drivers for Windows from here and install it.
  • Download ODIN from here and extract it.
  • T mobile S7 for flashing your T-Mobile S7 Edge device from here and extract it.
  • Hold the Volume Down + Power + Home button of your device simultaneously until you see options to Flash your device.
  • Now choose to move forward with flashing your device by pressing the  Volume up key on your device.
  • Now connect your device using a USB cable to your Windows PC.
  • Run ODIN as an admin and choose the files starting with BL, AP, CP  & CSC correspondingly into their respective fields and click on Start.
  • Wait for the flash operation to terminate successfully. This usually takes around 5-10 minutes depending on your hardware.
Categories
Uncategorized

Invisible reCAPTCHA with Angular 5

Install ng-recaptcha module and import it into the app.module.ts

Categories
interview

Front End Engineer Interview Prep

Classical Inheritance vs Prototypal Inheritance

The difference between classical inheritance and prototypal inheritance is that classical inheritance is limited to classes inheriting from other classes while prototypal inheritance supports the cloning of any object using an object linking mechanism. Read more here.

== vs ===

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. 

Closure

This property of Javascript allows for private variables in a function. For example

const increment = (() => {
  let counter = 0;
  return () => {
    counter += 1;
    console.log(counter);
  }
})();
// Self invoking function.

increment();
increment();
increment();

Demo

This is one common scenario you might run into when you use async calls inside a loop. The loop executes before the async call returns and the desired output is not logged.

function httpGet(theUrl, callback) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send(null);
}

for (var i = 0; i < 5; i++) {
  httpGet('https://httpbin.org/get', function(data) {
    console.log(i);
  });
}

Demo

Output

5
5
5
5
5

Using closure we can handle this in the following way

function httpGet(theUrl, callback) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send(null);
}

for (var i = 0; i < 5; i++) {
  ((index) => {
    httpGet('https://httpbin.org/get', function(data) {
      console.log(index);
    })
  })(i);
}

/*     or in ES6 you can simply use the 'let' keyword.   */

for (let i = 0; i < 5; i++) {
  httpGet('https://httpbin.org/get', function(data) {
    console.log(i);
  });
}

Demo

Output

0
1
2
3
4

Hoisting

The variables in javascript can be declared even after they are used as they are moved to the top of the code during execution. Hoisting doesn’t take place for initializing though. The same goes with function hoisting.

Note: There is no variable/function hoisting in ES6.

Strict Mode

When ‘use strict’ is used you will need to declare variables while using them. There are other rules such as not being able to delete objects etc when using this mode.

 Bubbling vs Capturing

Event propogation can be of 2 types Bubbling and Capturing.

Bubbling

Event propogation occurs starting from the inner element to the outermost element.

Capturing

Event propogation starts from the outermost element to innermost element. This is also known as Trickling.

Event Delegation

If a lot of elements are handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor.

event.target vs event.currentTarget

Events bubble by default. So the difference between the two is:

  • target is the element that triggered the event (e.g., the user clicked on)
  • currentTarget is the element that the event listener is attached to Read more…

Event Loop

Javascript event loop

Promises

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

REST API design

REST stands for representational state transfer. API stands for Application programming interface. Read here.

Pixel Pipeline

Pixel Pipeline

Read more here.

async await

Read more here.

What happens when you type google.com into address bar?

Read more here.

Performance optimization

Stick to compositor-only properties. Read more here.

JWT (JSON Web Token)

Read more here.

Local storage vs Session storage vs Cookies

The localStorage and sessionStorage objects are part of the web storage API, are two great tools for saving key/value pairs locally. Using localStorage and sessionStorage for storage is an alternative to using cookies and the data is saved locally only and can’t be read by the server, which eliminates the security issue that cookies present. It allows for much more data to be saved (10MB). Cookies are still useful, especially when it comes to authentication, but there are times when using localStorage/sessionStorage may be a better alternative.
Read more here & here.

Beacon API

The Beacon API is a web API that allows you to send small amounts of data from a web page to a web server, asynchronously and without delaying the loading of the next page. This API is typically used for analytics and performance monitoring purposes.

 const data = {
  event: 'button_click',
  timestamp: Date.now(),
  user_id: '12345',
};

// Send data to the server asynchronously using the Beacon API
navigator.sendBeacon('/api/log-event', JSON.stringify(data));

Server-sent events

Server-Sent Events (SSE) is a technology that enables a server to push real-time updates to a web client over a single HTTP connection. SSE is often used for applications that require real-time updates, such as live scoreboards, news feeds, or chat applications. SSE is used for light weight one way communication from server to client. Here’s an example of how to use Server-Sent Events in a web application:

Server-Side (Node.js with Express):

  1. First, you’ll need to set up a server that sends SSE updates to clients. Here’s a simple Node.js server using the Express framework:
const express = require('express');
const app = express();

// Serve a simple HTML page to the client
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// SSE route for sending updates
app.get('/sse', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  // Send a message to the client every 1 second
  setInterval(() => {
    res.write(`data: ${JSON.stringify({ message: 'Hello, world!' })}\n\n`);
  }, 1000);
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

In this example, the server sends a message to the client every second using an SSE endpoint (/sse).

2. Client-Side (HTML and JavaScript):Next, you’ll create an HTML page that listens to SSE updates and displays them. Here’s an example index.html file:

<!DOCTYPE html>
<html>
<head>
  <title>SSE Example</title>
</head>
<body>
  <h1>Server-Sent Events Example</h1>
  <div id="sse-data"></div>

  <script>
    const sseDataElement = document.getElementById('sse-data');

    // Create an EventSource object to listen for SSE updates
    const eventSource = new EventSource('/sse');

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      sseDataElement.innerHTML = `Message from server: ${data.message}`;
    };
  </script>
</body>
</html>

When you run this code, you should see “Hello, world!” messages displayed on the HTML page, updated every second, coming directly from the server.

HTTP long polling

HTTP long polling is a technique used to achieve real-time updates or push notifications from a server to a client over the HTTP protocol, even in scenarios where full-duplex communication like WebSockets is not available. In long polling, the client sends a request to the server, and the server holds the request open until new data becomes available or a timeout occurs. When new data is ready, the server responds to the client’s request, and the client immediately sends another request to keep the connection open.

const http = require('http');
const url = require('url');

// In-memory storage for messages (replace with a database in a production scenario)
const messages = [];

const server = http.createServer((req, res) => {
  const reqUrl = url.parse(req.url, true);

  if (reqUrl.pathname === '/poll') {
    const timeout = 30000; // You can adjust the timeout as needed (e.g., 30 seconds)
    const startTime = Date.now();

    const checkForMessages = () => {
      if (messages.length > 0) {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: messages.shift() }));
      } else if (Date.now() - startTime > timeout) {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'timeout' }));
      } else {
        setTimeout(() => {
          checkForMessages();
        }, 1000); // Polling interval (1 second)
      }
    };

    checkForMessages();
  } else if (reqUrl.pathname === '/push' && req.method === 'POST') {
    let requestBody = '';
    req.on('data', chunk => {
      requestBody += chunk.toString();
    });

    req.on('end', () => {
      const parsedBody = JSON.parse(requestBody);
      const message = parsedBody.message;

      if (message) {
        messages.push(message);
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ status: 'Message added to the queue' }));
      } else {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ status: 'No message provided' }));
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

In this Node.js example:

  1. The server handles incoming HTTP requests and distinguishes between the /poll and /push endpoints.
  2. For /poll, it waits for messages to become available and responds when a message is ready or when a timeout occurs.
  3. For /push, it accepts POST requests to add messages to the queue.
  4. Messages are stored in memory, but you should replace this with a database or more robust storage mechanism in a production scenario.

Client (HTML/JavaScript)

<!DOCTYPE html>
<html>
<head>
  <title>HTTP Long Polling Example</title>
</head>
<body>
  <div id="messages"></div>

  <script>
    const messagesDiv = document.getElementById('messages');

    function pollServer() {
      fetch('/poll')
        .then(response => response.json())
        .then(data => {
          if (data.message) {
            messagesDiv.innerHTML += '<p>' + data.message + '</p>';
          }
          pollServer(); // Continue polling
        })
        .catch(error => {
          console.error('Error:', error);
          pollServer(); // Continue polling even in case of errors
        });
    }

    // Start polling when the page loads
    pollServer();
  </script>
</body>
</html>

Garbage Collection

Reference counting vs Mark and Sweep. Read more here.

HTML Element as a datastore

Is Element in view

Js filter() polyfill

Javascript call() vs apply() vs bind()

Singleton Pattern

Shallow copy vs deep copy

Debounce

Throttling using Queue

Currying

Script async vs defer

Render Directory Structure

Smooth Animation

Flatten Array

getElementById() polyfill using BFS

Use DFS to flatten Javascript Objects

Implementing a Trie in Javascript

Find identical node in DOM Tree

Valid Parentheses

Overview of XSS & CSRF, How do you combat them?

Create a carousel component

Create a component to render Google Photos

Create a component to render auto complete suggestions

Create a component to render a table with filter and sort capabilities

Create a component to render a Chat App