Ten-X Interview

1) Write a javascript function to print an array slowly (e.g each element in intervals of 500 ms). Example of array : 1,5,6,’cool’,8. Once done then print “all done”.

Method-1

var arr = [1,5,6,"cool",8];

function foo(i) {
   console.log("i:" + i + ":" + arr[i]);

}

function foo2() {
   console.log("all done");
}

for (i=1; i <=3 ; i++) {
    setTimeout(foo, i*500, i);
}

setTimeout(foo2, (i)*500);

Disadvantage in Method-1 is that so many setTimeout will be in memory. In Method-2 the number of setTimeout in memory will be less.

Method-2

var arr = [1,5,6,'cool', 8];

function foo(i) {
if (i < arr.length) {
console.log("i:" + i + ":" + arr[i]);
setTimeout(foo, 500, i+1);
} else {
console.log("all done");
}
}

setTimeout(foo, 500, 0);

Method-3

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  // using the ES6 let syntax, it creates a new binding
  // every single time the function is called
  // read more here: http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads
  setTimeout(function() {
    console.log('The index of this number is: ' + i);
  }, 3000*i);

Method-4

for (i = 0, max = 9; i < max ; i ++) {
  setTimeout(printFunc(i), 500*i);
}

function printFunc(i) {
   return function() {
       console.log(i);
   }
}

Method-5. (Using IIFE – Immediately Invoked Function Expression)

var arr = [1,5,6,"cool",8];

for (i=0; i < arr.length ; i++) {
   (function(i) {
    setTimeout(foo, i*1500, i);
   }(i))
}
function foo(i) {
   console.log("i:" + i + ":" + arr[i]);

}

function foo2() {
   console.log("all done");
}


setTimeout(foo2, (i)*1500);

 

2) Given a string “San Francisco Hotel” and a array of strings (e.g. San Jose Culture of Art, Father Francisco and San Mateo”, “Yahoo”, “I love Hotel”) etc find out the best match. For example in above “Father Francisco and San Mateo is best match since it contains San and Francisco.

You can index all given individual strings. For example “San”, “Jose”, “Culture”, “Art”, etc  mapping name to index of string where it appears.

San ==> array(0,1)

Jose ==> array (0)

Culture ==> array(0)

Art ==> array(0)

Father ==> array(1)

Francisco ==> array(1)

Mateo ==> array(1)

Hotel ==> array(3)

Then to search for an input string, You can get all the results for each word in the input string and combine the resultant set in a hash which contains which word occurs how many times.

For San Francisco Hotel you will need to show strings : 0,1,3 for sure. However to rank these strings you can use a hash which will show you which word appears more times.

result[1] ==> 2  (string at index 1 contains 2 matching words)

result[0] ==> 1 (string at index 0 contains 1 matching word)

result[3] ==> 1  (string at index 3 contains 1 matching word)

 

3) Given a sorted array return a random array.

4) Given an array of N numbers return the max product of 3 numbers. Example if the array contains [4,2,7,5,3] then the max product possible is 4 * 7 * 5 = 140.

5) In Javascript Using functional programming , given an array of numbers, return the sum of their squares.

var arr = [2,4,6,8];

var sum = arr.map(function(s) { return s*s;}).reduce(function(acc, val) {return acc + val;});

Way to create an object in Javascript

1) // object constructor

var mango =  new Object ();
mango.color = "yellow";
mango.shape= "round";
mango.sweetness = 8;

mango.howSweetAmI = function () {
console.log("Hmm Hmm Good");
}
      

2) // object literal

      // This is an object with 4 items, again using object literal
var mango = {
color: "yellow",
shape: "round",
sweetness: 8,

howSweetAmI: function () {
console.log("Hmm Hmm Good");
}
}
   

3) // constructor pattern

function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {

    this.color = theColor;
    this.sweetness = theSweetness;
    this.fruitName = theFruitName;
    this.nativeToLand = theNativeToLand;

    this.showName = function () {
        console.log("This is a " + this.fruitName);
    }

    this.nativeTo = function () {
    this.nativeToLand.forEach(function (eachCountry)  {
       console.log("Grown in:" + eachCountry);
        });
    }


}

var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
   

4) // using prototype pattern

function Fruit () {

}

Fruit.prototype.color = "Yellow";
Fruit.prototype.sweetness = 7;
Fruit.prototype.fruitName = "Generic Fruit";
Fruit.prototype.nativeToLand = "USA";

Fruit.prototype.showName = function () {
console.log("This is a " + this.fruitName);
}

Fruit.prototype.nativeTo = function () {
            console.log("Grown in:" + this.nativeToLand);
}

var mangoFruit = new Fruit ();
   

5) // using Object.create()

var superHuman = {
    usePower: function () {
        console.log(this.superPower + "!");
    }
};

var banshee = Object.create(superHuman, {
    name: { value: "Silver Banshee" },
    superPower: { value: "sonic wail" }
});

// Outputs: "sonic wail!"
banshee.usePower();

Difference between Object.create() and new SomeFunction()

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)

http://adripofjavascript.com/blog/drips/basic-inheritance-with-object-create.html

http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction

Static Concept

A static variable is one that’s associated with a class, not objects of that class.

Static is an access qualifier that limits the scope but causes the variable to exist for the lifetime of the program. This means a static variable is one that is not seen outside the function in which it is declared but which remains until the program terminates. It also means that the value of the variable persists between successive calls to a function.

void fun() { 
    static int fnvalue=0;//Executed once 
    printf(" \n%d",fnvalue++);// Value changed retains for next call 
} 

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class.

Features of Object Oriented Programming

Encapsulation:
Encapsulation is a mechanism by which you restrict the access to some of the object’s components, as well as binding the data and methods operating on the data. Encapsulation is a way to obtain ‘information hiding’.

Abstraction:
Abstraction is the process of moving from a specific idea to a more general one. For example take your mouse. “Silver Logitech MX518” is a concrete, specific item, and “mouse” is an abstraction of that.

Inheritance:

Polymorphism:
Displaying multiple behavior. Achieved via virtual functions, operator overloading, function overloading, etc

Virtual Function: Without “virtual” you get “early binding”. Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through. With “virtual” you get “late binding”.

Virtual Constructor:

Stack vs Heap

The Stack

What is the stack? It’s a special region of your computer’s memory that stores temporary variables created by each function (including the main() function). The stack is a “LIFO” (last in, first out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is “pushed” onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.

The advantage of using the stack to store variables, is that memory is managed for you. You don’t have to allocate memory by hand, or free it once you don’t need it any more. What’s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.

A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).

Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be stored on the stack. This is not the case for variables allocated on the heap.

To summarize the stack:

  • the stack grows and shrinks as functions push and pop local variables
  • there is no need to manage the memory yourself, variables are allocated and freed automatically
  • the stack has size limits
  • stack variables only exist while the function that created them, is running

The Heap

The heap is a region of your computer’s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free() to deallocate that memory once you don’t need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won’t be available to other processes). As we will see in the debugging section, there is a tool called valgrind that can help you detect memory leaks.

Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.

Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.

Stack vs Heap Pros and Cons

Stack

  • very fast access
  • don’t have to explicitly de-allocate variables
  • space is managed efficiently by CPU, memory will not become fragmented
  • local variables only
  • limit on stack size (OS-dependent)
  • variables cannot be resized

Heap

  • variables can be accessed globally
  • no limit on memory size
  • (relatively) slower access
  • no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
  • you must manage memory (you’re in charge of allocating and freeing variables)
  • variables can be resized using realloc()

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap.

https://www.gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html