Nitin Agrawal
Contact -
  • Home
  • Interviews
    • Secret Receipe
    • InterviewFacts
    • Resume Thoughts
    • Daily Coding Problems
    • BigShyft
    • CompanyInterviews >
      • InvestmentBanks >
        • ECS
        • Bank Of America
        • WesternUnion
        • WellsFargo
      • ProductBasedCompanies >
        • CA Technologies
        • Model N India
        • Verizon Media
        • Oracle & GoJek
        • IVY Computec
        • Nvidia
        • ClearWaterAnalytics
        • ADP
        • ServiceNow
        • Pubmatic
        • Expedia
        • Amphora
        • CDK Global
        • CDK Global
        • Epic
        • Sincro-Pune
        • Whiz.AI
        • ChargePoint
      • ServiceBasedCompanies >
        • Altimetrik
        • ASG World Wide Pvt Ltd
        • Paraxel International & Pramati Technologies Pvt Ltd
        • MitraTech
        • Intelizest Coding Round
        • EPAM
    • Interviews Theory
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems
      • AnagramsSet
    • Core Java >
      • Codility
      • Program Arguments OR VM arguments & Environment variables
      • Java Releases
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
        • Future Or CompletableFuture
      • Important Points
      • Immutability
      • Dictionary
      • URL Validator
    • Julia
    • Python >
      • Decorators
      • String Formatting
      • Generators_Threads
      • JustLikeThat
    • Go >
      • Tutorial
      • CodeSnippet
      • Go Routine_Channel
      • Suggestions
    • Methodologies & Design Patterns >
      • Design Principles
      • Design Patterns >
        • TemplatePattern
        • Adapter Design Pattern
        • Decorator
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • RequestChaining
        • Singleton >
          • Singletons
  • Frameworks
    • Apache Velocity
    • Spring >
      • Spring Boot >
        • CustomProperties
        • ExceptionHandling
        • Issues
      • Quick View
    • Rest WebServices >
      • Interviews
      • Swagger
    • Cloudera BigData >
      • Ques_Ans
      • Hive
      • Apache Spark >
        • ApacheSpark Installation
        • SparkCode
        • Sample1
        • DataFrames
        • RDDs
        • SparkStreaming
        • SparkFiles
    • Integration >
      • Apache Camel
    • Testing Frameworks >
      • JUnit >
        • JUnit Runners
      • EasyMock
      • Mockito >
        • Page 2
      • TestNG
    • Blockchain >
      • Ethereum Smart Contract
      • Blockchain Java Example
    • Microservices >
      • Messaging Formats
      • Design Patterns
    • AWS >
      • Honeycode
    • Dockers >
      • GitBash
      • Issues
  • Databases
    • MySql
    • Oracle >
      • Interview1
      • SQL Queries
    • Elastic Search
  • Random issues
    • TOAD issue
    • Architect's suggestions
  • Your Views
// print array elements like - 1,2,3,4
// Array of any length can be used here
Array.prototype.print = function() {
 console.log(this.join(','));
};
[1,2,3].print();
===============================================================================================
//Passing a declaration of the function to other function
function x(a) {
return a+1;
}
let y = function(x) {
return x+2;
}
console.log(y(3));
===============================================================================================
// Find the number of occurences of the maximum number in te given array
arr = [1,2,2,4,3,4,5];
let maxN = Math.max(...arr);
console.log("Count of maximum number : "+arr.filter(a=>a === maxN).length);

//Give the output of the below code
arr = [100,200,2,400,3,4,50];
for(let i = 0; i < arr.length; i++) {
setTimeout(() => {
console.log("Index :"+ i + " element : " + arr[i]);
}, arr[i]);
}
===============================================================================================
//Convert the given time to 24 Hr format
let time = '09:03PM';
let arr = time.split(':');
if(time.indexOf('PM') > 0) {
let hr = 12+parseInt(arr[0]);
console.log(hr+":"+arr[1].split('P')[0]);
} else if(time.indexOf('AM') > 0) {
console.log(time);
} else {
console.log("Wrong input");
}
===============================================================================================
//Create an array of different size arrays of elements of different types
// Access any element from this array of arrays
let arr = [
[1,2,3],
[4,5,6,"7"]
]
console.log(`Value is ${arr[1][3]}`)

let arr = [1,2,3,4,5]
console.log(arr.push("stop")); // this will print the size of the array after push()
console.log(arr.unshift("start")); // this will print the size of the array after unshift()
console.log(arr);
console.log(["start",...arr]); // This works for ES6 & it will not update the arr but will will print   
                               //   the new contents, to store the result in arr do the following
arr = ["start",...arr, "stop"];
console.log(arr);
===============================================================================================
//Output of below will be 2
var num = 4

function outer() {
var num = 3;
function inner() {
num++;
//console.log(num);
var num = 2;
console.log(num);
}
inner();
}
outer();
===============================================================================================
// Accessing the functions & properties
var person = {
_name:"Nitin",
 getName : function() {
return this._name;
}
};

var name = person.getName;
console.log("Indirect : " + name());
console.log("Direct : " + person.getName());

===============================================================================================
var obj = {
val : 3
}

function add(a) {
var sum = 0;
console.log("Number of arguments : " + arguments.length);
// use this block if getting multiple arguments
/*for(let i of arguments) {
sum+=i;
}*/
sum = a.reduce(function(a,b) {return a+b;}, 0); // This way will work if getting the arguments as an  
                                                //array
console.log(this.val+sum);
}

//add.apply(obj, [1,2,3]); //apply() will expand the elements of the array & will pass, as can see in          
                           //number of arguments result
add.call(obj, [1,2,3]); //call() will pass it as an array object to add()
var bound = add.bind(obj); // This is another way to call a function for the properties of another object, i.e. bind that object with the method,
                           // This bind() will return the bounded function
bound([1,2,3]); //This execute the above bounded function for the given arguments, here array of numbers is the argument, so reduce() will work for  
                //this.
===============================================================================================
//Sorting the array of objects based on some property
var arr = [{
id : 3,
name : 'Nitin'
}, {
id : 1,
name : 'Seth'
}, {
id : 5,
name : 'Ali'
}, {
id : 2,
name : 'Hina'
}
]

arr.sort(function (val1, val2) {
if(val1.name<val2.name)
return 1;
else
return -1;
});

for(obj of arr) {
console.log(obj.name);
}

arr.sort(function (val1, val2) {
return val1.id - val2.id;
});

for(obj of arr) {
console.log(obj.id);
}
===============================================================================================
//Find the extension of the file name provided
var getExtension = (file) => file.slice(file.lastIndexOf('.'))
console.log(getExtension('abc.xyz.txt'));
===============================================================================================
// increase every char in string to next char, so that output for below input will be - bcde
var moveChars = (str) => 
str.split('')
   .map(char => String.fromCharCode(char.charCodeAt(0)+1))
   .join('');

console.log(moveChars('abcd'));
===============================================================================================
let cleanroom = function() {
console.log("Cleaning Room...");
return new Promise(function(done, notDone) {
console.log("Cleaned the Room...");
done('Room is cleaned')});
};

let removeGarbage = function(message) {
console.log("Removing garbage...");
return new Promise(function(done, notDone) {
console.log("Removed the garbage...");
done(message+', Garbage is removed')});
}

let gotIceCream = function(message) {
console.log("Getting icecream...");
return new Promise(function(done, notDone) {
console.log("Got the icecream...");
done(message+', Icecream is given')});
}

//Below will start all given tasks & once any one task is completed, will return that promise.
Promise.race([cleanroom, removeGarbage, gotIceCream]).then(function(result){
console.log('Any one Completed...')});
//Below will start all given tasks & once all are completed, will return that promise.
/*Promise.all([cleanroom, removeGarbage, gotIceCream]).then(function(result){
console.log('All Completed...')});*/
//Below way each task is executed in given order only
/*cleanroom().then(function(result){
return removeGarbage(result);
}).then(function(result){
return gotIceCream(result);
}).then(function(result){
console.log('Finished...'+result)
})*/
===============================================================================================
// Let us see the impact/behavior when delay is added to each function
let cleanroom = function() {
console.log("Cleaning Room...");
return new Promise(function(done, notDone) {
setTimeout(() => {
console.log("Cleaned the Room...");
done('Room is cleaned')}, 4000);
});
};

let removeGarbage = function(message) {
console.log("Removing garbage...");
return new Promise(function(done, notDone) {
setTimeout(() => {
console.log("Removed the garbage...");
done(message+', Garbage is removed')}, 5000);
});
}

let gotIceCream = function(message) {
console.log("Getting icecream...");
return new Promise(function(done, notDone) {
setTimeout(() => {
console.log("Got the icecream...");
done(message+', Icecream is given')}, 3000);
});
}

//Below will start all given tasks & once any one task is completed, will return that promise.
/*Promise.race([cleanroom, removeGarbage, gotIceCream]).then(function(result){
console.log('Any one Completed...')});*/
//Below will start all given tasks & once all are completed, will return that promise.
/*Promise.all([cleanroom, removeGarbage, gotIceCream]).then(function(result){
console.log('All Completed...')});*/
//Below way each task is executed in given order only
cleanroom().then(function(result){
return removeGarbage(result);
}).then(function(result){
return gotIceCream(result);
}).then(function(result){
console.log('Finished...'+result)
})
===============================================================================================
//This operator was introduced in ES6
var obj = {a:1,b:2};
console.log(obj.a);
const{a} = obj; //It should have the same properties names as exist in obj, else it will either give undefined or error will be thrown
({b} = obj); //one can use this way also using () with no const
console.log(a)
console.log(b)
===============================================================================================
// This is why let is used in loops, just try to change let to var, you will see the difference
var obj = {a:1,b:2};
console.log(obj.a);
const{a} = obj;
({b} = obj);
console.log(a);
console.log(b);
for(let i = 0; i < 10; i++) {
console.log(i);
}
console.log(i);
===============================================================================================
// Way to check if the variable is an array
var arr = [1,2,3,4];
console.log(arr instanceof Array);
console.log(Array.isArray(arr))
===============================================================================================
// Find if the given character occurs in the given string for certain number of times
var counting = (str, ch) => {
return str.split('').filter(c => c===ch).length;
}

var checking = (str, ch, min, max) => {
var count = counting(str, ch);
return count >= min && count <= max ? true : false;
}

console.log(checking('abhh', 'a', 2, 3));
===============================================================================================
// passing a function to other function
// Use this method when you need to pass the value from one function to other function
// And suppose that first function takes time to get the value & in second function it depends
// on some condition if that value will be required or not. Then why to calculate the value in
// advance rather pass that first function to second function where first function will be executed
// when required.
var fun = function(a) {
console.log(`In function`);
if(false) // Time taking function is not executed, so why to calculate the value in advance.
console.log(a(2,3));
}

var s = new fun((a,b) => {
return a+b // Time taking step
});
s;
===============================================================================================
var fun = function(a) {
console.log(`In function`);
if(false)
console.log(a(2,3));
}

var s = new fun((a,b) => {return a+b});
s;​
===============================================================================================
//Below check every executable statment is executed in the order they are present in the code
// as JS is interpreted language
function start() {
console.log('In start()');
}
var exec = (function fun() {
console.log('In fun()');
return 'return from fun()';
})();

console.log('after fun()');
console.log(exec);
start();​
Powered by Create your own unique website with customizable templates.