Coding interview questions:
Javascript is the official language of all modern web browsers. As such, Javascript questions come up in all sorts of developer interviews.
Apart from theoretical knowledge, we may encounter some coding questions. Some of those are below. Please go through these and crack the interviews. If you come across any other than these, please mention below in the comments section.
Get the smallest number in an array:
var arr = [2, 3, 10, 6, 4, 8, 1];
var min = arr[0];
for(var i=0; i<arr.length; i++) {
if(min>arr[i]) {
min = arr[i];
}
}
console.log(min);
Get the largest number in an array:
var arr = [2, 3, 10, 6, 4, 8, 1];
var max = arr[0];
for(var i=0; i<arr.length; i++) {
if(max<arr[i]) {
max = arr[i];
}
}
console.log(max);
Maximum difference between two elements such that larger element appears after the smaller number:
var arr = [2, 3, 10, 6, 4, 8, 1];
var maxDiff = getMaxDiff(arr);
function getMaxDiff(a) {
var diff = [];
for(var i = 0; i<a.length; i++) {
var ref = a[i];
for(var j=i+1; j<a.length; j++) {
if(ref<a[j]) {
diff.push(a[j]-ref);
}
}
}
console.log(diff);
var max = diff[0];
for(var i=0; i<diff.length; i++){
if(max < diff[i]) {
max = diff[i];
}
}
console.log(max);
}
Quick sort:
/*
Choose first element as pivot element(index 0)
start looping through array (from index 1)
if any of the array elements is less than pivot element, then push it to (or make that element part of left array otherwise of right array)
*/
var a = [12, 6, 2, 1, 4, 20, 0];
var quickSortedArray = quickSort(a);
console.log(quickSortedArray)
function quickSort(arr) {
if(arr.length < 2) {
return arr;
}
var pivot = arr[0];
var left = [], right = [];
for (var i = 1; i< arr.length; i++) {
if( arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return (quickSort(left).concat(pivot, quickSort(right)));
}
Bubble sort:
let a = [50, 75, 300,2, 0, 99, 1, 5, 100, 300] ;
var arrayWithUniqueEles = getArrayWithUniqueEles(a);
var sortedArray = getBubbleSortedArray(arrayWithUniqueEles);
console.log(sortedArray);
function getArrayWithUniqueEles(a) {
var b = [];
a.map((ele, index) => {
(b.indexOf(ele) !== -1) ? '' : b.push(ele);
});
return b;
}
function getBubbleSortedArray(array) {
for(var i=0; i<array.length; i++) {
for(var j=0; j<array.length-i-1; j++) {
if(array[j] > array[j+1]) {
var temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
return array;
}
Get 'k' largest numbers in an array:
let a = [50, 75, 300,2, 0, 99, 1, 5, 100, 300] ;
var arrayWithUniqueEles = getArrayWithUniqueEles(a);
var sortedArray = getBubbleSortedArray(arrayWithUniqueEles);
console.log(sortedArray.slice(-3));//largest 3 elmenetas;
function getArrayWithUniqueEles(a) {
var b = [];
a.map((ele, index) => {
(b.indexOf(ele) !== -1) ? '' : b.push(ele);
});
return b;
}
function getBubbleSortedArray(array) {
for(var i=0; i<array.length; i++) {
for(var j=0; j<array.length-i-1; j++) {
if(array[j] > array[j+1]) {
var temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
return array;
}
Factorial of a given number:
function FirstFactorial(num) {
var factorial = 1;
while(num>1) {
factorial *= num;
num--;
}
return factorial;
}
console.log(FirstFactorial(6));
Segregate 0s and 1s:
var a = [1,0,1,0,1,1,0,0,0,1,1]; segregateElements(a); function segregateElements(arr) { var count = 0; for(var i = 0; i<a.length; i++) { if(a[i] === 0) { count++; } }//count will be 5 for(var i=0; i<count; i++) { a[i] = 0; } for(var i=count; i<a.length; i++) { a[i] = 1; } console.log(a); }
Segregate Even and odd numbers:
var a = [2,4,5,7,8,1,9];//method 1
segregateEvenOddNumbers(a);
function segregateEvenOddNumbers(arr) {
var even = [];
var odd = [];
var segregatedArray = arr.map(function(ele){
if(ele%2 == 0) {
even.push(ele);
} else {
odd.push(ele);
}
})
var newArr = even.concat(odd);
console.log(newArr);
}
/* 1) Initialize two index variables left and right:
left = 0, right = size -1
2) Keep incrementing left index until we see an odd number.
3) Keep decrementing right index until we see an even number.
4) If left < right then swap arr[left] and arr[right] */
Check if array has duplicate elements:
var a = [30, 23, 17, 23, 1, 5, 3, 9, 0, 3, 30];
function hasDuplicates(array){
var b = [];
array.map(function(ele) {
(b.indexOf(ele) !== -1) ? '' : b.push(ele) ;
});
console.log(b);
}
hasDuplicates(a);
Fibonacci series
function fibonacci(num)
{
var eles = [0, 1];
var num1=0;
var num2=1;
var sum;
var i=0;
if(num === 1) {
return 0;
} if(num === 2) {
return 1;
}
for (i = 0; i < num; i++)
{
sum=num1+num2;
num1=num2;
num2=sum;
eles.push(num2);
}
return eles;
return num2;
}
console.log(fibonacci(5));
currying.js
const mul = (a, b) => {
return a * b;
};
mul(2,3);
function mul(a) {
return function(b) {
return a * b;
};
};
const mul = a => b => a * b;
mul(2)(3);// mul(2) returns a fn; pass 2nd arg to it
// import redux from 'redux';
const redux = require('redux');
const createStore = redux.createStore;
const INCREMENT_COUNT = 'INCREMENT_COUNT';
const INCREMENT_COUNT_MUTATE = 'INCREMENT_COUNT_MUTATE';
const DECREMENT_COUNT = 'DECREMENT_COUNT';
const incrementCount = () => {
return {
type: INCREMENT_COUNT,
somePayload: ''
}
}
const incrementCountMutate = () => {
return {
type: INCREMENT_COUNT_MUTATE,
somePayload: ''
}
}
const initialState = {
count: 0,
anotherProp: 0,
someArr: []
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT_COUNT:
return {
...state,
count: state.count + 1
}
case DECREMENT_COUNT:
return {
...state,
count: state.count - 1
}
case INCREMENT_COUNT_MUTATE:
state.someArr.push(1);
default:
return state;
}
};
const store = createStore(reducer);
//Gets the current state
console.log('initialState::', store.getState());
// Allow the app to subscribe to changes in the store; The callback to be invoked any time an action has been dispatched, and the state tree might have changed.
const unsubscribe = store.subscribe(() => {
console.log('updatedState::', store.getState());
});
store.dispatch(incrementCount());
store.dispatch(incrementCount());
store.dispatch(incrementCount());
console.log('Before unsubscribe::', store.getState());
// unsubscribe();
// A function that unsubscribes the change listener.
console.log('After unsubscribe::', store.getState());
store.dispatch(incrementCount());
store.dispatch(incrementCount());
console.log('Finally::', store.getState());
store.dispatch(incrementCountMutate());
console.log('Finally123::', store.getState());
fp.js
// import { compose, pipe } from 'lodash/fp';
const { toLower } = require('lodash');
const { Map } = require('immutable');
const { compose, pipe } = require('lodash/fp');
//------------- FUNCTIONS AS FIRST CLASS CITIZENS
function getParadigm() {
return "Functional Programming";
};
let a = getParadigm;// 1/ "someString"/ true/ false; Not calling the nf; Simply passing a reference to it
console.log('calling a::', a());
console.log('calling getParadigm::', getParadigm());
// Passing as an argument to a function
function showParadigm(fnMessage) {
console.log(fnMessage());
};
showParadigm(getParadigm);
// fn can be returned from other functions
function getParadigmm() {
return function() {
return "Functional Programming";
}
}
let b = getParadigmm();
let msg = b();
console.log('msg: ', msg);
//--------------- HIGHER ORDER FUNCTIONS
// Examples: showParadigm, getParadigmm
let numbers = [1, 2, 3];
numbers.map(number => number + 7); // map is HOF bcs it takes fn as an arg
setTimeout(() => console.log('Hello from setTimeout'), 1000); // setTimeout is HOF bcs it takes fn as an arg
//-------------FUNCTION COMPOSITION
// Non-functional style of code:
let input = ' Javascript ';
let output = `<div>${input.trim().toLowerCase()}</div>`;
console.log('Non-Functional result:', output);
/* Functional way of writing code
- trim
- wrapInDiv
- toLowerCase
*/
const trim = str => str.trim();
const wrapInDiv = str => `<div>${str}</div>`;
const toLowerCase = str => str.toLowerCase();
const result = wrapInDiv(toLowerCase(trim(input)));
console.log('Functional result with lot of parenthesis n reading expression from RTL:', result);
//------------------COMPOSING AND PIPING
const composedResult = compose(wrapInDiv, toLowerCase, trim);// simply, passing references
console.log('Compose example without parenthesis:', composedResult(input));
/*
- compose is a HOF bcs it takes bunch of functions as i/p
- It solved parenthesis issue but still have the right to left reading. To solve this we've pipe
*/
const transform = pipe(trim, toLowerCase, wrapInDiv);
console.log('Pipe example without parenthesis and LTR:', transform(input));
// -------------------CURRYING
const wrapInSpan = str => `<span>${str}</span>`;// wrapInSpan, wrapInDiv looks similar. It'd be better if we parameterize it
const wrap = (type, str) => `<${type}>${str}</${type}>`;
console.log(pipe(trim, toLowerCase, wrap)); // <javascript>undefined</javascript>
/*
output of 1 fn is the ip of next fn
wrap (type(javascript), str(undefined))
*/
// console.log(pipe(trim, toLowerCase, wrap("div")));// we'll get an error: Expected a function
// Every arg to the pipe() has to be a fn;
// wrap("div") returns a string `<${type}>${str}</${type}>`
// we cannot build a pipeline with a bunch of functions and string
// Pipeline needs a function with 1-parameter; in this case output of toLowerCase(); no other parameters
// currying a fn
const curriedWrap = type => str => `<${type}>${str}</${type}>`;
const curriedTransform = pipe(trim, toLowerCase, curriedWrap("span")); // pass div to curriedWrap and see
console.log('Result with currying:', curriedTransform(input));
// -----------------PURE FUNCTIONS
//Impure ex
function isSeniorCitizen(age) {
return age > minAge;// minAge is a global state;
}
//Pure ex
function isSeniorCitizen(age, minAge) {
return age > minAge;// minAge is not a global state;
}
// Cacheability
const add = n => n + 10;
const memoizedAdd = () => {
let cache = {};
return (n) => {
console.log('cache:', cache);
if (n in cache) {
console.log('From cache');
return cache[n];
} else {
console.log('New input');
let result = n + 10;
cache[n] = result;
return result;
}
}
};
const newAdd = memoizedAdd();
console.log('memoized addition: ', newAdd(9));
console.log('memoized addition: ', newAdd(2));
console.log('memoized addition: ', newAdd(3));
console.log('memoized addition: ', newAdd(9));
//-------------------IMMUTABILITY
let name = "Redux";
let newName = name.toUpperCase();//name remains the same
let book = {};
book.title = "Redux";// Objs n arrays are mutable in js. Bcs js is not pure FP language, it's a
// multi paradigm. But we can still apply FP concepts.
// -----------------UPDATING OBJECTS
const employee = {
name: 'X'
};
// 1st way of updating an object
const newEmpUsingAssign = Object.assign({}, employee, {age: 30, name: 'Z'});
console.log(`newEmpUsingAssign: ${newEmpUsingAssign}`);
// 2nd way of updating an object
const newEmpUsingSpread = {...employee, salary: 7};
// Shallow copy vs deep copy
const emp = {
name: 'Y',
address: {
country: 'INDIA',
city: 'Hyderabad'
}
};
const shallowCopiedEmp = {...emp};
shallowCopiedEmp.address.city = "Kakinada";// Mutating; It'll change the actuall object; Because it's a shallow copy
const deepCopiedEmp = {
...emp,
address: {
...emp.address,
city: 'Bangalore'
}
}
// --------------------UPDATING ARRAYS
const nums = [1, 2, 3];
// Adding
const updatedArr = [...nums, 4];
const index = nums.indexOf(2);
const added = [...nums.slice(0, index), 4, ...nums.slice(index)];
// Remove
const res = nums.filter(n => n !== 2);
//Update
const updatedNums = nums.map(n => n === 2 ? 20 : n);
// --------------------IMMUTABLEJS
let bookObj = {
title: "Redux"
};
function publish(book) {
book.isPublished = true;// Mutation of global state
};
publish(bookObj);
// With ImmutableJs
let immutableBook = Map({
title: "Redux"
}); // it's not a regular object
console.log(immutableBook);//
console.log(immutableBook.get('title'));
console.log(immutableBook.toJS());
const updated = immutableBook.set('isPublished', true);// It's not gonna modify the original object; It returns a new object; Because all these Map objects are immutable; That's why we've to reassign the immutableBook variable
console.log('updated: ', updated);// it won't get updated
console.log(immutableBook.toJS());// To get a plain JS object
console.log(immutableBook.get('isPublished'));
immutableBook = immutableBook.set('isPublished', true);// It'll be updated with a new property
console.log(immutableBook.toJS());
/* ==============================
IMMER
============================== */
let myBook = {
title: "ReduxToolkit"
};
function publishIt(book) {
return produce(book, draftBook => {// 2nd arg to produce is a fn that specifies our mutation
draftBook.isImmer = true;// this is mutating code
});// book won't get changed. draftBook is kind of proxy to book that records all the changes we're making to book; takes copy of this obj and apply all the chnages. wriing the code as if we're mutating the obj but actually not; produce returns updated obj. so we've to return it
}
let updatedBook = publishIt(myBook);
console.log('updatedBook: ', updatedBook);
No comments:
Post a Comment