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;
}
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
//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));
//Solution 1
//es-6
firstArray.filter(el=> !secondArray.includes(el));
//es-5
firstArray.filter(function(el) {
return (secondArray.indexOf(el) === -1);
});
//es-6
[...string].reverse().join('')
//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;
}
//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)
}
}
if(var !== null && typof var == 'object')
- 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 usinguse strict
mode or we will get error if not then it will leak to the global scope (i.e. in browser is window).
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);
}
Answer:
Above function will work :)
- 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.
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.
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.
}
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.