Interview Questions- Part-15

compose

				
					//acc is arg first time i,e -->5
//acc = arg=5
//...functions --> add, add, mul
//step 1--> curFunc(acc) --> add(5) --> 5 + 5 -->10--> acc is 10 now
//step 2--> curFunc(acc) --> add(10) --> 10 + 10 --> acc is 20 now
//step 3--> curFunc(acc) --> mul(20) --> 20 * 20 --> acc is 400 now
//400 is returned now
//arg is used only once --> the input 5

const add = (x) => x + x;
const mul = (x) => x * x;
const div = (x) => x / x;

const compose = (...functions) => {
  return (arg) => {
    return functions.reduce((acc, curFunc) => {
      console.log("acc is arg first time i,e -->5 -->10(5+5)-->20(10+10) -->400(20*20)" + acc);
      console.log("curFunc will be function: add -->add-->mul" + curFunc);
      console.log("args will be always 5-->this will be used first time..." + arg);
      return curFunc(acc);
    }, arg);
  };
};

const output = compose(add, add, mul);
console.log(output(5));
				
			

Guess the output -- Answer in comment section

				
					const add = (x) => x + x;
const mul = (x) => x * x;
const div = (x) => x / x;

const compose = (...functions) => {
  return (arg) => {
    return functions.reduce((acc, curFunc) => {
      return curFunc(acc);
    }, 4);
  };
};

const output = compose(add, add, mul);
console.log(output(5));
				
			

Before Memoize

				
					

const calculation = (x) => {
  for (let i = 0; i < 10000000; i++) {
    x += 1;
  }
  return x;
};



console.time("1st call");
console.log(calculation(1)); //1st call: 14.338134765625 ms
console.timeEnd("1st call");



				
			

After Memoize

				
					const memoize = (fun, context) => {
  const output = {};
  console.log("fun::" + fun);
  return function (...args) {
    var argumentCache = JSON.stringify(args);
    console.log("output::" + JSON.stringify(output)); //at start this will be {}..later will have value
    if (!output[argumentCache]) {
      console.log("context::" + context); //undefined
      console.log("this::" + this); //undefined
      console.log("args::" + args); //1

      //...Use either call or apply....
      //output[argumentCache] = fun.call(context || this, ...args); //call will take as normal args...
      output[argumentCache] = fun.apply(context || this, [...args]); //apply will take array...
    }
    return output[argumentCache];
  };
};

const calculation = (x) => {
  for (let i = 0; i < 10000000; i++) {
    x += 1;
  }
  return x;
};

const newCalculation = memoize(calculation);
console.log(newCalculation);
// newCalculation is nothing but below function...
// ƒ (...args) {
//   var argumentCache = JSON.stringify(args);
//   console.log("argumentCache::" + argumentCache);
//   console.log("output::" + JSON.stringify(output));
//   if (!output[argumentCache])…

console.time("1st call");
console.log(newCalculation(1)); //1st call: 14.338134765625 ms
console.timeEnd("1st call");

console.time("2nd call");
console.log(newCalculation(1)); //2nd call: 0.076171875 ms
console.timeEnd("2nd call");

				
			

let vs var - Random question

				
					{
  let x = "Can I be accessed outside this block ??";
}
//Uncaught ReferenceError: x is not defined
//console.log(x);

{
  var x = "Seems I can be accessed outside this block....";
}
//Seems I can be accessed outside this block....
console.log(x);
				
			

let vs var - Random question

				
					//This is allowed as var can be re-declared...
const question1 = () => {
  var x = "I am x";
  if (true) {
    var x = "I am getting modified...";
  }
};
question1();

//you cannot do this...as let variable cant be re-declared...
const question2 = () => {
  let x = "I am x";
  if (true) {
    var x = "I am getting modified...";
  }
};
				
			

Calculate Average in number array

				
					//calculate average of the array

let numbers = [1, 2, 3, 4, 5];
//average is -->15/5 =3

//attempt1
let sum = numbers.reduce((acc, curr) => acc + curr);
console.log(sum / numbers.length);

//attempt2
let avg = numbers.reduce((acc, curr, index, arr) => {
  if (arr.length === index + 1) {
    return (acc + curr) / arr.length;
  }
  return acc + curr;
}, 0);
console.log(avg);

				
			

prototypal inheritence

				
					let Study = function (course, level, isAvailableOnPs) {
  this.course = course;
  this.level = level;
  this.isAvailableOnPs = isAvailableOnPs;

  this.courseLevel = function () {
    console.log(this.course + " is for " + this.level);
  };
};

Study.prototype.IsAvailableOnCoursera = function () {
  if (this.isAvailableOnPs) return `${this.course} is available on PluralSight`;
  else return `No ${this.course} is not available on PluralSight!!`;
};

let study1 = new Study("Javascript", "Beginners", true);
let study2 = new Study("Advanced Javascript", "Professionals", false);

study1.courseLevel();
study2.courseLevel();

// Javascript is for Beginners
// Advanced Javascript is for Professionals
// ES new concepts is for Proficient

//Prototypal inheritance..
//Every Object has prototype --> where you can add methods and properties to it
//When you create newly created object using prototype-> the newly created object will
//automatically inherit the properties and methods from already existing parent
//It will try to find out in newly created object first--> if it doesnt find ,,will look for parent object

console.log(study1.IsAvailableOnCoursera());
console.log(study2.IsAvailableOnCoursera());

//Javascript is available on PluralSight
//No Advanced Javascript is not available on PluralSight!!
				
			

Guess the output

				
					let A = { a: 1, b: 2 };
let B = A;
B.x = 20;
console.log(A.x); //20
				
			

Assign negative index or string in array- behaves like object

				
					let num = [1, 2, 3, 4];
num[-1] = 50;
num["name"] = "anurag";
console.log(num);
// (4) [1, 2, 3, 4, -1: 50, name: 'anurag']
// 0: 1
// 1: 2
// 2: 3
// 3: 4
// -1: 50
// name: "anurag"
// length: 4

//************Key points ********** */
//Outupt--> Array behaves like object
//you can access below num[-1] or num["name"] like object properties
//num[-1] --> 50 , num["name"] --> "anurag"
//Length is still 4 -- not 6
console.log(num[-1]); //50
console.log(num["name"]); //anurag
console.log(num.length); //4

//************Key points ********** */
// Lets loop - using for in
// As you know we can loop objects using for in...

for (let x in num) {
  console.log(`Key -->:${x} :: Value --> ${num[x]}`);
}

//output
// Key -->:0 :: Value --> 1
// Key -->:1 :: Value --> 2
// Key -->:2 :: Value --> 3
// Key -->:3 :: Value --> 4
// Key -->:-1 :: Value --> 50
// Key -->:name :: Value --> anurag
				
			

slice vs splice

Splice --> Original array gets affected

Slice --> Original array doesnt get impacted...

				
					//* Slice vs Splice *//
let num = [1, 2, 3, 4, 5, 6, 7];
let res1 = num.slice(1, 3);
let res2 = num.slice(2, 5);
console.log(res1); //[2,3]
console.log(res2); //[3, 4, 5] --> explained below
console.log(num); //[1,2,3,4,5,6,7]

//*SLICE//
//let num = [1, 2, 3, 4, 5, 6, 7];
//FIRST PARAMETER
//0-->1, 1-->2, 2-->3 , 3--> 4 , 4-->5, 5-->6 , 6-->7
//SECOND PARAMETER
//1-->1, 2-->2, 3-->3 , 4--> 4 , 5-->5, 6-->6 , 7-->7
//let res2 = num.slice(2, 5); -->> [3,4,5]
//ORIGINAL ARRAY IS NOT AFFECTED...

let res3 = num.splice(1, 3);
console.log(res3); //[2,3,4]
console.log(num); //[1,5,6,7]
//*SPLICE//
//At position 1 - remove 3 items ..
//position 1 is --> 2
//Remove 3 items is in res3 -->2 ,3 ,4
//original num array becomes --> [1,5,6,7]
//ORIGINAL ARRAY IS AFFECTED...

				
			

Cool Array.from usages

				
					let empName = "Anurag";
console.log([...empName]); //['A', 'n', 'u', 'r', 'a', 'g']
console.log(Array.from(empName)); //['A', 'n', 'u', 'r', 'a', 'g']
// create array of length 10 using Array.from ..fill with numbers cube

const createNewArray1UsingFrom = Array.from({ length: 10 }, (val, index) => index * index * index);
console.log(createNewArray1UsingFrom); //[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
const createNewArray1UsingFill = new Array(10).fill(0).map((val, index) => index * index * index);
console.log(createNewArray1UsingFill); //[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

//Remove Duplicates using Array.from
let num = [1, 2, 2, 2, 3, 4, 5];
console.log(Array.from(new Set(num))); //[1, 2, 3, 4, 5]

//
let characters = ["A", "N", "U", "R", "A", "G"];
//combine
console.log(Array.from(characters).join("")); //ANURAG
				
			

Leave a Comment