Skip to content

Instantly share code, notes, and snippets.

@satyajeetkrjha
Last active April 14, 2023 01:15
Show Gist options
  • Save satyajeetkrjha/dca6f2bbd9f71228bf127c6d4588ba90 to your computer and use it in GitHub Desktop.
Save satyajeetkrjha/dca6f2bbd9f71228bf127c6d4588ba90 to your computer and use it in GitHub Desktop.
Javascript interview questions
// write an asynchronous function which executes callback after asynchronous task
const asyncFunction = (callback) =>{
setTimeout(()=>{
callback('done');
},2000);
}
asyncFunction((message)=>{
console.log('callback ',message);
})
//Design a class for employee which takes id and name in during construction of object and has a salary property
//Design a class which is manager and can have department property
class Employee{
constructor(id,name){
if(!id || !name){
throw new Error('Employee id and name are mandatory');
}
this.id = id ;
this.name = name ;
}
setSalary(salary){
this.salary = salary ;
}
getSalary(){
return this.salary;
}
getName(){
return this.name;
}
getId(){
return this.id;
}
}
class Manager extends Employee{
setDepartment(name){
this.deapartment = name ;
}
getDepartment(){
return this.deapartment;
}
}
const employee = new Employee(1,"Satya");
employee.setSalary(100);
const manager = new Manager(2,'John');
manager.setDepartment('CS');
console.log(employee.getSalary());
console.log(manager);
console.log("working");
const users =[
{
id:1,
name:"Jack",
isAactive :false
},
{
id:2,
name:"Jack2",
isAactive :true
},
{
id:3,
name:"Jack3",
isAactive :true
},
]
const activeUsersSortedByAge
= users && users.sort((user1,user2)=> (user1.age <user2.age ? 1:-1)).filter((user)=> user.isAactive === true).map((item)=> item.name);
const userNames = users && users.map((item)=>item.name); // get all names of users
const activeUsers = users.filter ((item)=> item.isAactive == true).map((item)=> item.name); // get all names of users
console.log(activeUsers);
console.log(userNames);
let names =[];
users.forEach((user)=>{
names.push(user && user.name);
})
console.log('names',names);
// write a function which helps to achieve multiply(a)(b) and return products of a and b .
const multiply =(num1)=>{
return (num2)=>{
return num1*num2 ;
}
}
console.log(multiply(10)(2));
//Need to study again
// write a function which helps to achieve multiply(a)(b) and return products of a and b .
const multiply =(num1)=>{
return (num2)=>{
return num1*num2 ;
}
}
console.log(multiply(10)(2));
// create a curry function
// we want our curried sum
// what we are trying to build is const curriedSum = curry((a,b,c)=> a+b+c);
const curry = function(fn){
return function f1(...args){
const arity = args.length;
if(args.length >=arity){
return fn(...args);
}
else{
return "Need more arguments";
return function f2(...moreargs){
var newargs = args.concat(moreargs);
return f1(...newargs);
}
}
}
}
const curriedSum = curry((a,b,c)=> a+b+c);
// console.log(curriedSum(10,20,30));
const partiallycurried = curriedSum(1);
console.log(partiallycurried(1,2));
//Create debounce function
//Function will be called only first certain period of time
//Every single call of this function will be delayed
const saveInput =(name)=>{
console.log('saveinput ',name);
}
const debounce = (fn,timeout = 3000)=>{
let timer ;
return (...args) =>{
console.log('inner function ',args);
clearTimeout(timer);
timer =setTimeout(()=>{
fn.apply(this,args);
},timeout)
}
}
const processChange = debounce(saveInput,2000);
processChange("foo");
processChange("foo");
processChange("foo");
processChange("foo");
processChange("foo");
// write an example of getting data from fetchApi
import fetch from "node-fetch";
let url ='https://api.github.com/users/schacon/repos';
fetch(url)
.then((res)=>{
res.json()
})
.then((res)=>{
console.log("data ",res.data);
})
const arr = [1, 2, 3, [4, 5, [6, 7, [8, 9, 10]]]]
const flattenArray = (arr)=>{
let newArray =[]
const flatten = (arg)=>{
arg.forEach((item,index)=>{
if(Array.isArray(item)){
flatten(item);
}
else{
newArray = [...newArray,item]
}
})
};
flatten(arr);
return newArray;
}
const res = flattenArray(arr);
console.log(res);
let var1 ;
console.log(var1); // undefinned
console.log(typeof var1); // undefined
let var2 = null;
console.log(var2);
console.log(typeof var2);
console.log(foo); // ReferenceError: foo is not defined
foo =1 ;
console.log(foo); // output is undefined because var declaration bubbles into the top of the file .Hoisting
var foo =1 ;
console.log(foo); // ReferenceError: foo is not defined .
let foo =1 ;
foo =3 ;
console.log(foo);
var foo ;
// output should be 3 because the var declaration of foo is now bubbled at the top so we can think that var foo exists even before foo=3 is declared
// bubbles to the top
foo(); // no errors
function foo(){
}
const STATE = {
PENDING: 'PENDING',
FULFILLED: 'FULFILLED',
REJECTED: 'REJECTED',
}
function isThenable(val) {
return val instanceof MyPromise;
}
class MyPromise {
constructor(callback) {
this.state = STATE.PENDING;
this.value = undefined;
this.handlers = [];
try {
callback(this._resolve, this._reject);
} catch (err) {
this._reject(err)
}
}
_resolve = (value) => {
this.updateResult(value, STATE.FULFILLED);
}
_reject = (error) => {
this.updateResult(error, STATE.REJECTED);
}
updateResult(value, state) {
// This is to make the processing async
setTimeout(() => {
// process the promise if it is still in pending state
if (this.state !== STATE.PENDING) {
return;
}
// check is value is also a promise
if (isThenable(value)) {
return value.then(this._resolve, this._reject);
}
this.value = value;
this.state = state;
// execute handlers if already attached
this.executeHandlers();
}, 0);
}
addHandlers(handlers) {
this.handlers.push(handlers);
this.executeHandlers();
}
executeHandlers() {
// Don't execute handlers if promise is not yet fulfilled or rejected
if (this.state === STATE.PENDING) {
return null;
}
// We have multiple handlers because add them for .finally block too
this.handlers.forEach((handler) => {
if (this.state === STATE.FULFILLED) {
return handler.onSuccess(this.value);
}
return handler.onFail(this.value);
});
// After processing all handlers, we reset it to empty.
this.handlers = [];
}
then(onSuccess, onFail) {
return new MyPromise((res, rej) => {
this.addHandlers({
onSuccess: function(value) {
// if no onSuccess provided, resolve the value for the next promise chain
if (!onSuccess) {
return res(value);
}
try {
return res(onSuccess(value))
} catch(err) {
return rej(err);
}
},
onFail: function(value) {
// if no onFail provided, reject the value for the next promise chain
if (!onFail) {
return rej(value);
}
try {
return res(onFail(value))
} catch(err) {
return rej(err);
}
}
});
});
}
// Since then method take the second function as onFail, we can leverage it while implementing catch
catch(onFail) {
return this.then(null, onFail);
}
// Finally block returns a promise which fails or succeedes with the previous promise resove value
finally(callback) {
return new MyPromise((res, rej) => {
let val;
let wasRejected;
this.then((value) => {
wasRejected = false;
val = value;
return callback();
}, (err) => {
wasRejected = true;
val = err;
return callback();
}).then(() => {
// If the callback didn't have any error we resolve/reject the promise based on promise state
if(!wasRejected) {
return res(val);
}
return rej(val);
})
})
}
}
const testPromiseWithLateResolve = new MyPromise((res, rej) => {
setTimeout(() => {
res('Promise 1 is resolved')
}, 1000);
});
testPromiseWithLateResolve.then((val) => {
console.log(val);
});
const testPromiseWithLateReject = new MyPromise((res, rej) => {
setTimeout(() => {
rej('Promise 2 is rejected')
}, 1000);
});
testPromiseWithLateReject.then((val) => {
console.log(val);
}).catch((err) => {
console.log(err);
});
const testPromiseWithRejectFinally = new MyPromise((res, rej) => {
setTimeout(() => {
rej('Promise 2 is rejected')
}, 1000);
});
testPromiseWithRejectFinally.finally(() => {
console.log('finally called');
}).catch((err) => {
console.log('value rejected after finally', err);
});
const testPromiseWithEarlyResolve = new MyPromise((res, rej) => {
res('Promise 3 is resolved early')
});
setTimeout(() => {
testPromiseWithEarlyResolve.then((val) => {
console.log(val);
});
}, 3000);
// Create a function which has increment and getValue functionality
//This is a really good example of closure beacuse we see that inside increment and getValue function
// we have access to the count varaible .Closure basically means if you are inside a function ,you have access
// to everything defined above or before it
const privateCounter = () =>{
let count =0;
return {
increment :(val=1) =>{
count+=val
},
getValue:()=>{
return count ;
}
}
}
const counter = privateCounter();
console.log(counter);
console.log(counter.count);
console.log(counter.getValue());
counter.increment();
console.log(counter.getValue());
const privateSecret = ()=>{
const secret = 'password';
return () => secret ;
}
const getSecret = privateSecret();
console.log(getSecret());
//Find the number of occurences of minimum value in the list
const arr = [9,8,3,3,4];
const minValue = Math.min(...arr);
const minArray = arr.filter((element)=>element == minValue);
console.log( minArray.length);
function myPromiseAll(allPromises){
const results =[];
let promisesCompleted =0;
return new Promise((resolve ,reject)=>{
allPromises.forEach((promise,index)=>{
promise.then((val)=>{
results[index] = val;
promisesCompleted+=1;
if(promisesCompleted === allPromises.length){
resolve(results);
}
}).catch((error)=>{
reject(error);
})
})
})
}
function myPromiseRace(promises){
return new Promise((resolve ,reject)=>{
promises.forEach((promise,index)=>{
promise.then((va)=>{
resolve(val);
}).catch((err)=>{
reject(err);
})
})
})
}
//Design a class for employee which takes id and name in during construction of object and has a salary property
//Design a class which is manager and can have department property
var Employee = function(id,name){
if(!id || !name){
throw new Error('Employee id and name are mandatory');
}
this.id = id ;
this.name = name ;
}
Employee.prototype.setSalary = function(salary){
this.salary = salary ;
}
Employee.prototype.getSalary = function(){
return this.salary;
}
Employee.prototype.getName = function(){
return this.name;
}
Employee.prototype.getId = function(){
return this.id;
}
var Manager= function(params){
Employee.apply(this,arguments);
this.iamge = params.image ;
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor =Manager ;
Manager.prototype.setDepartment= function(name){
this.deapartment = name ;
}
Manager.prototype.getDepartment= function(){
return this.deapartment;
}
const employee = new Employee(1,"Satya");
employee.setSalary(100);
const manager = new Manager(2,'John');
manager.setDepartment('CS');
console.log(employee.getSalary());
console.log(manager);
// Write a function which implements range
// range (1,50)
// 1,2 3,4.....,50
const range = (start,end) =>{
return [...Array(end).keys()].map((el)=>el+start);
}
console.log(range(10,20));
//Remove all duplicates
const numbers = [1,2,2,3];
const uniqueNumbers = (arr)=>{
return [...new Set(arr)];
}
console.log(uniqueNumbers([1,2,2,3]));
const unique = (arr)=>{
let result = [];
arr.forEach((item)=>{
if(!result.includes(item)){
result.push(item);
}
})
return result;
}
console.log(unique([1,2,2,2,3,3,4]));
// write a function which implememts shuffle
const shuffleItems = (items)=>{
return items.map((item)=>({sort:Math.random(),value:item}))
.sort((item1,item2)=> item1.sort -item2.sort)
.map((item)=>item.value)
;
}
console.log(shuffleItems([1,2,3]));
const books =[
{name:'book1',author:'author1 jha'},
{name:'book2',author:'author2 aha'},
{name:'book3',author:'author lha'}
];
const sortedBooks = books.sort((book1,book2)=>{
const authorlastName1 = book1.author.split(' ')[1];
const authorlastName2 = book2.author.split(' ')[1];
return authorlastName1 <authorlastName2 ? -1:1;
});
console.log(books);
console.log(sortedBooks);
function getItem(){
// this prints out window object
//does not always refer to window object
console.log(this);
}
getItem();
// this time
//this { title: 'Ball', getItem: [Function: getItem] }
// when we are talking about object this always reference ours object
const Item ={
title:"Ball",
getItem(){
console.log("this ",this);
}
};
Item.getItem();
//Create throttle function
//Function will be executed immediately
const saveInput =(name)=>{
console.log('saveinput ',name);
}
const throttle = (fn,timeout = 3000)=>{
let isWaiting = false;
return (...args) =>{
console.log('inner function ',args);
if(!isWaiting){
fn.apply(this,args);
isWaiting = true;
setTimeout(()=>{
isWaiting = false;
},timeout)
}
}
}
const processChange = throttle(saveInput,2000);
processChange("foo0");
setTimeout(()=>{
processChange("foo1000");
},1000);
setTimeout(()=>{
processChange("foo1200");
},1200);
setTimeout(()=>{
processChange("foo2400");
},2400);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment