Skip to content

Instantly share code, notes, and snippets.

@lokeshjain2008
Last active April 13, 2016 06:49
Show Gist options
  • Save lokeshjain2008/d1f83a5ce4a1ada382b260f5025db309 to your computer and use it in GitHub Desktop.
Save lokeshjain2008/d1f83a5ce4a1ada382b260f5025db309 to your computer and use it in GitHub Desktop.

Programming Questions

Use a programming language of your choice

1. Complete the function caffeineBuzz, which takes a non-zero integer as it's one argument.

If the integer is divisible by 3, return the string "Java". If the integer is divisible by 3 and divisible by 4, return the string"Coffee" If the integer is one of the above and is even, add "Script" to the end of the string. Otherwise, return the string "mocha_missing!" caffeineBuzz(1) => "mocha_missing!" caffeineBuzz(3) => "Java" caffeineBuzz(6) => "JavaScript" caffeineBuzz(12) => "CoffeeScript"

function caffeineBuzz(number) {
  let message = "mocha_missing";

  if(number%3 == 0) {
    message = 'Java';
    if(number%4 == 0) {
      message = "Coffee";
    }

    if(number%2 == 0) {
      message += 'Script';
    }
  }

  return message;
}

2. What are closures? Give an example. Why would it be usefull in a programming language.

Answer: The most simple way to think of a closure is a function that can be stored as a variable , that has a special ability to access other variables local to the scope it was created in.

function BaseCounter() {
  // will become private variable
  let counter = 0;

  function upFucntion() {
    //rember the variable;
    counter++;
  }

  function downFunction() {
    counter--;
  }

  function showFunction() {
    return counter;
  }

  return{
    up: upFucntion,
    down: downFunction,
    show: showFunction
  };

}

var myCounter = BaseCounter();

myCounter.up();
myCounter.up();
myCounter.show(); //Other code can't change the value of counter by accident. as counter is so common name;
//2

3. Identify and remove duplicates from an array/list.

//solution 1
// es 5
var arrayIndetifier = {};
var duplicates =[];

list = list.filter(function(el) {
  if(arrayIndetifier[el]){
    duplicates.push(el);
    return false;
  }else{
    arrayIndetifier[el] = 1;
    return true;
  }
});

//solution 2
//es-6 to remove duplicates

list = Array.from(new Set(list));

4. Given 2 arrays find the values not present in the second one. eg [1,2,3,4,5] [4,5,6,7,8] = 1,2,3

//Solution 1
//es-6
  firstArray.filter(el=> !secondArray.includes(el));

//es-5
  firstArray.filter(function(el) {
    return (secondArray.indexOf(el) === -1);
  });

5. Reverse a string in-place, i.e., change "I am a good" to "doog a ma I"

  //es-6
  [...string].reverse().join('')

6. Write a function to verify a word as a palindrome.

//es-2015 solution one
var isPalindrom = str => str === [...str].reverse().join('');

//es-5 solution 2
function isPalindrom(str) {
  var len = Math.floor(str.length / 2);
  for (var i = 0; i < len; i++)
    if (str[i] !== str[str.length - i - 1])
      return false;
  return true;
}

7. An unsorted array has 1 to 1000 numbers, except one number. Find the missing number.

  //There are many solution for this particular problem.
  // I choose the addition and math formula for this.

  var unsortedArray = [<random numbers>];

  // sum of all nutular numbers be

  var totalSumShouldBe = 1000 * 1001 /2
  // n(n+1) /2

  var totalSum = unsortedArray.reduce( val, el=> val+el);

  var missingNumber = totalSumShouldBe - totalSum;

Alternate language what I like ruby.

solution

 missingNumbersArray =  (1..1000).to_a - unsortedArray;

8. Extend the previous function to find 2 missing numbers. can it be extended to find n missing numbers?

Yeah, from ruby above solution will work for n missing numbers. let's try to solve this in javascript. :)

Some, math will be involved in the finding missing 2 numbers.

for the above solution we have found. x = sum of all - (sum of all -x), we got x. Here we need to find 2 let they are x and y.

we need two equation to get the 2 unknown. Note are are going for summation of powers not multiplecation of all numbers as there my may b a max number overflow.

sum of squares = a1^2 + a2^2+....

x^2 + y^2 = sumOfSquare of all - sum of square with missings.

So, x = sum of x+y - y

  // from the above solution.
  // sum of all nutular numbers be

  var totalSumShouldBe = 1000 * 1001 /2
  // n(n+1) /2

  var totalSum = unsortedArray.reduce( (val, el)=> val+el);

  var missingTwo = totalSumShouldBe - totalSum;

  // sum of squares
  //  n(n+1)(2n+1)/6
  var squaresSumShouldBe = (1000 * 1001 * 2001)/6 ;
  var squaresSum = unsortedArray.reduce( (val,el) => val+ el*el, 0);

  var missingTwoSq = squaresSumShouldBe - squaresSum;

  // x2+y2 =  missingTwoSq
  // x+y = missingTwo
  // (x+y)2 = x2+y2+2xy
  // xy = (missingTwo^2 - missingTwoSq)/2

  var missingTwoProduct = (missingTwo*missingTwo -  missingTwoSq) /2

  // now x+y and xy are known so y = missingTwoProduct/x   so, we can calculate both now.

If there are n element missing than the above approach will become pain.

//sorting required..
const getMissingElement = (array)=>{
  let storedArray = unsortedArray.sort(); //first step

  let  n = Math.max.apply(null, arr);  // get the maximum
  let result = [];
  for (let i=1 ; i<n ; i++) {
      if (arr.indexOf(i) < 0) result.push(i)
  }

}

Use JavaScript

1. How would you check if a variable is an object?

if(var !== null && typof var == 'object')

2. Explain the difference between

  • var x = 1 // this is called declaration and value assignment done properly and the scope of x will be own by the conatining function if any.
  • x = 1 // this is just assignment of the variable x. x should be declared before if we are using use strict mode or we will get error if not then it will leak to the global scope (i.e. in browser is window).

3. Write a function that accepts any number of arguments and returns their sum.

  var summation = function () {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(val,el) {
      if(el instanceof Array){
        el = el.reduce(function(val,el) {return val+el;});
      }
      return val+el;
    },0);
  }

4. Without modifying the function above, sum all the values in an array.

Answer:

Above function will work :)

5. What is the difference between

  • var function1 = function() {};
  • function function2() {}

Answer::

  • var function1 = function(){

}; This is style is called function expression. This will create function statement on the runtime. We can write conditional statement to add function for the variable declaration.

// will not be ready if call
function1(); //error
var function1 = function(){

};
function1(); // will work

It will reduce the confusion.

  • function function2(){

}

This is style is called function declaration. This is the classy way of writing functions in almost all the languages. Here function2 will b defined in the compile time. Will be hoisted.

function2() ; //will work
// We can call this before defination
function function2(){

}
function2(); // will work

This style can lead to confusion in a large code base.

6. Demonstrate with sample code how will you implement public, private, privileged methods.

Answer:: Ok, will show by sample code.

function Lokesh(){

  var fullName = "Lokesh kumar jain"; // private variable

  //private function can't be called outside of closing function.
  function homeWork (){
    // some stuff like dishes .... :)
  }

  //privilaged function
  this.doSomeWork =  function (){
    //have access to private variables and
    //private function
    homeWork();
  }

}

//public functions
Lokesh.prototype.publicWork = function(){
  //don't have access to private functions and variables.
}

Hope, code snippet is clear to understant.

7. Write an Ajax example using any framework of your choice that loads content

from an external file. The call should not refresh the page.

  //html5
  fetch('/<sumUrl>')
  .then((response)=>response.json())
  .then(
    //do what to do.
    )
  .catch();

  // Angular
  // we can use both `$http` and `$resource`. i will use `$resource` as it is REST oriented.
  // Note this depends on `ngResource` module.
  //
  $resource('/nexsales/users/:id', {'gender':"@gender"});

  //Jquery
  $.ajax( "/nexsales/data" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );

8. Is JavaScript a class-based or prototype-based language? How can you implement inheritance in JavaScript?

Answer :: JavaScript is prototype based language.

// es-5 way to implement inheritance

function Base(){

}

function Child(){
  Base.call(this,args);
}

Child.prototype = Object.create(Base.prototype);
//reset the constructor
Child.prototype.constructor = Child;


// es-6 way

class Base{

}

class Child extendes Base{
  super(args); //can call constructor of parent class.
}

9. What is the difference between 'undefined' and 'null'?

Answer: Both are primitive datatypes. but type of null is object. undefined is a placeholder if we don't assign the value to variable. null is a real value and we need to assing to the value.

var x;
console.log(x); // undefined
x = null;
console.log(x); // null

if(undefined || null){ //falsy
  console.log("will not print");
}

undefined and null both are considered as falsy values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment