Changing Context Of JavaScript Functions Using Call() And Apply()

// Create a global variable for context
var context = "Global (ie. window)";
// Create an object.
var objectA = {
  context: "Object A"
};
// Create another object.
var objectB = {
  context: "Object B"
};
// Define a function that uses an argument AND a reference
function testContext( approach ){
  console.log( approach, "==> THIS ==>", this.context );
}
             
// Invoke the unbound method with standard invocation.
testContext( "testContext()" );
              
// Invoke it in the context of Object A using call().
testContext.call(
    objectA,
    ".call( objectA )"
); 
          
// Invoke it in the context of Object B using apply().    
 testContext.apply(
     objectB,
     [ ".apply( objectB )" ]
);

objectA.testContext = testContext;
// Invoke it as a property of object A.
objectA.testContext( "objectA.testContext()" );

// Invoke it in the context of Object B using call.
objectA.testContext.call(
     objectB,
     "objectA.testContext.call( objectB )"
);

// Invoke it in the context of Window using apply.
objectA.testContext.apply(
     window,
     [ "objectA.testContext.apply( window )" ]
);
Advertisements

JavaScript Closure

Good

My Experience

What is JavaScript closure?

An inner function that has access the outer function’s variables

The closure has three scope chains:

  • it has access to its own scope
  • it has access to the outer function’s variables
  • it has access to the global variables

Example:

Demo

View original post

Interview Question for JavaScript

Rules

  • If input is “1-4”, output should be “1,2,3,4”.
  • If input is “1-4,6”, output should be “1,2,3,4,6”
  • Sort the Output in Asending order and no repeated number
  • Validate the input

HTML

<input type="text" id="userVal" placeholder="Enter value">
<button id="userSubmit" onclick="userOutputFun()">Submit</button>
<div id="userOutput"></div>

Javascript

function userOutputFun(){
	var userVal = document.getElementById("userVal").value;
  var allNum = getAllNumbers(userVal);
  if( !isValid(allNum) ){
  	document.getElementById("userOutput").innerHTML = "InValid Input";
  	return false;
  }
  var findUniqueNum = findUnique(allNum);
  var sortedVal = findUniqueNum.sort(function(a, b){return a-b});
  document.getElementById("userOutput").innerHTML = sortedVal.join(",");
}
function getAllNumbers(userVal){
	var arr1 = userVal.split(",");
  var arr2 = [];
  for(var i = 0; i < arr1.length; i++){
  	var arr3 = arr1[i].split("-");
  	if(arr3.length == 1){
    	arr2.push(arr3[0]);
    }
    else{
    	for(var j = parseInt(arr3[0]); j < parseInt(arr3[1])+1; j++){
      	arr2.push(j);
      }
    }
  }
  return arr2;
}

function findUnique(allNum){
	var arr = [];
  recursiveFun(allNum);
  function recursiveFun(allNum){
  	arr = [];
    for(var i = 0; i < allNum.length; i++){
      for(var j = 0; j < allNum.length; j++){
				if( allNum[i] == allNum[j] && i !== j ){
        	allNum.splice(j, 1);
          return recursiveFun(allNum);
        }
      }  
      arr.push(allNum[i]);
    }
  }
  return arr;
}

function isValid(userVal){
	for( var i = 0; i < userVal.length; i++ ){
  	if( !parseInt(userVal[i]) ){
    	return false;
    }
  }
  return true
}


DEMO HERE

Find Happy Number Using JS

What is happy number?

A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum
of the squares of its digits, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). DEMO

function isHappyChecker(n) {
 		var arr = [];
    var newNum = 0;
  	var arr = n.toString().split(&quot;&quot;);
    for (var i = 0; i &lt; arr.length; i++) {
         newNum += Math.pow(arr[i], 2);
     }
     if (newNum === 1) {
				alert(&quot;it is a happy number&quot;);
         return true;
     } else {
     //here I noticed that all unhappy numbers eventually came into one of these three//
     //( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//       
         if (newNum === 58 || newNum === 4 || newNum == 37) {
        	   alert(&quot;it is a NOT happy number&quot;);
             return false;
         }
         return isHappyChecker(newNum);
     }
  }