Categories
interview

Window.location object

Javascript can access the URL of the current page with window.location object. This object contains various properties of the URL such as protocol, host, pathname, search and more.

  • window.location.href returns the href (URL) of the current page
  • window.location.hostname returns the domain name of the web host
  • window.location.pathname returns the path and filename of the current page
  • window.location.protocol returns the web protocol used (http: or https:)
  • window.location.assign() loads a new document
<button class="newDocument">
   New Document
</button>
console.log(window.location.href); //"https://fiddle.jshell.net/_display/?editor_console=true"

console.log(window.location.hostname); //"fiddle.jshell.net"

console.log(window.location.pathname); //"/_display/"

console.log(window.location.protocol); //"https:"

//Window.location.assign - click on the "New Document" button to load a new document.

function newDocument() {
  window.location.assign("https://www.collegestash.com/")
}

const newDocButton = document.querySelector(".newDocument");

newDocButton.addEventListener('click', newDocument);

Demo

Categories
interview

Staircase using repeat()

Runtime Complexity: O(n^2)

/*Create a staircase based on user input n.

steps(5) should return the below output:
"#    "
"##   "
"###  "
"#### "
"#####" 
*/

const steps = (n) => {
if( n > 0){
  for (let row = 0; row < n; row++) {
      let step = '';

      for (let col = 0; col < n; col++) {
        col <= row ? step += '#' : step += ' ';
      }
       console.log(step);
   }
   return
}
console.log(`please give a number greater than 0`)
}

steps(5);
/* Output
"#    "
"##   "
"###  "
"#### "
"#####" */

Demo

String.prototype.repeat()

Introduced in ES2015+, the repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

Syntax: str.repeat(count)
count is an integer between 0 and infinity(positive) indicating the number of times to repeat the string.

CodeOutput
‘abc’.repeat(-1)RangeError
‘abc’.repeat(0)
‘abc’.repeat(1)‘abc’
‘abc’.repeat(2)‘abcabc’
‘abc’.repeat(3.5)‘abcabcabc’ // Uses floor
‘abc’.repeat(1/0)Range Error

Note: If the total length of the string to be returned equals or exceeds (1 << 28, i.e., 2^28) then, this method throws a RangeError as most modern browsers can’t handle strings longer than that.

if((str.length * count) >= 1 << 28) // This 
/* A simplified solution using String.prototype.repeat
 */
 
 const steps = (n) => {
  for(let i = 1; i <= n; i++) {
    let step = '#'.repeat(i) + ' '.repeat(n-i);
    console.log(step);
  }
}

steps(5);
/* Output
"#    "
"##   "
"###  "
"#### "
"#####" */

Demo

Categories
interview

Generator Functions in JavaScript:

Introduction

ES6 introduced new type of functions called Generator Functions. A function keyword with an asterisk * is used to define a generator function.

function* generatorFunction(i) {
  yield i;
  yield i + 10;
}
const generator = generatorFunction(1);
console.log(generator.next().value); //1
console.log(generator.next().value); //11

Demo

A Generator Function can be called as many times as desired. Every time the function is called it returns a special type of iterator object called Generator. Generators are unique, calling the function by next() method returns a new Generator. The next() method returns an object with a Value property containing the yield value and a done property which is a Boolean indicating whether the generator has yielded its last value.

//Normal functions 

function normalFunction() {
  console.log("cannot");
  console.log("be");
  console.log("stopped");
}

normalFunction()// cannot be stopped

//Generator function

function* generatorFunction() {
  yield console.log("can");
  yield console.log("be");
  yield console.log("stopped");
}

const generator = generatorFunction();
generator.next().value; // can
generator.next().value; // be
generator.next().value; // stopped

Demo

Memory Efficient

Generator Functions are memory efficient, they can be stopped midway or suspend function execution to yield values on demand and continue from where it was stopped by calling next().

They are efficient when iterating over a large data set(or an infinite list). Most of the time we may not want to iterate through the full list and want to generate only what is needed at that time.

function* generatorFunction(max) {
    let number = 0;

    //iterate over an infinite count to generate squared numbers

    while (number < max) {
      number++;
      yield number * number;
    }
  }

  const max = Infinity;

  let iterationCount = 0;
  
  const totalIterations = 5;

  const squaredNumber = generatorFunction(max);

  //generate first 5 squared numbers
  
  while (iterationCount < totalIterations) {
    iterationCount++;
    console.log(squaredNumber.next().value);
  }

Demo

Using Return in the Generator Function

When the return statement gets executed then the done property will be set to true. Any subsequent next() method will not be executed. Note that any error that is not caught in the function execution will finish the function as well and returns.

function* generatorWithReturn(i) {
  yield i; //returns i
  return i; //returns i
  yield i; //returns undefined
}

var gen = generatorWithReturn("conitnue")
console.log(gen.next()); // { value: "continue", done: false }
console.log(gen.next()); // { value: continue, done: true }
console.log(gen.next()); // { value: undefined, done: true }

Demo