JS Interview Series - 2

·

2 min read

Hey All,

As I said before, I want to add/solve questions that I encountered in my interviews. Therefore we can improve ourselves together. And I am pretty sure these questions will help someone else in their future interviews. Without further ado, let's deep dive into codes.

Write fibonacci function in imperative and then in recursive and then try to increase recursive function's performance with cached recursive and finally write it in tail recursive

function fibonacciImperative(num) {
  let [previous, current] = [0, 1];
  if (num <= 0) {
    return previous;
  }
  if (num === 1) {
    return current;
  }
  for (let i = 2; i <= num; i++) {
    [previous, current] = [current, previous + current];
  }
  return current;
}

function fibonacciRecursive(num) {
  if (num <= 1) {
    return num;
  }
  return fibonacciRecursive(num - 1) + fibonacciRecursive(num - 2);
}
function fibonacciRecursiveWithCache(n) {
  const fiboStore = new Map([
    [0, 0],
    [1, 1],
  ]);
  function inner(num) {
    if (fiboStore.has(num)) {
      return fiboStore.get(num);
    }
    const fibonacci = inner(num - 1) + inner(num - 2);
    fiboStore.set(num, fibonacci);
    return fibonacci;
  }
  return inner(n);
}

function fibonacciTailRecursive(num, previous = 0, current = 1) {
  if (num === 0) {
    return previous;
  }
  if (num === 1) {
    return current;
  }
  return fibonacciTailRecursive(num - 1, current, previous + current);
}

console.log("fibonacciImperative: ", fibonacciImperative(20));
console.log("fibonacciRecursive: ", fibonacciRecursive(20));
console.log("fibonacciRecursiveWithCache: ", fibonacciRecursiveWithCache(20));
console.log("fibonacciTailRecursive: ", fibonacciTailRecursive(20));

Write a curried product function that can be called in various ways defined below.

product(2,3,4,5)(); // 120
product(2,3)(4,5)(); // 120
product(2)(3)(4)(5); // 24
function product(...args){ 
    return function(...args1){
        if(args1.length === 0){
            return args.reduce((acc,num) => acc * num);
        }
        return product(...args,...args1);            
    }     
}

I think a code snippet means 1000 words. If you have any questions about the code please do not hesitate to contact me.

Stay tuned, bye bye

Did you find this article valuable?

Support Chety's Blog by becoming a sponsor. Any amount is appreciated!