For first one: function chunkArray(arr, chunkSize) { let map = {}; let i = 0; if (chunkSize < 0) throw new Error("Chunk side should be greater than 0"); if (chunkSize >= arr.length) return [arr]; while (i < arr.length) { let currentChunk = arr.slice(i, Math.min(i + chunkSize, arr.length)); map[i.toString()] = currentChunk; i += chunkSize; } return Object.values(map); }
All the questions are amazing. Solved Chunk problem using splice. function chunk(arr, size) { if (size > arr.length) { return [arr]; } let count = Math.ceil(arr.length/size), result = [], startIndex = 0; for(let i = 0; i < count; i ++) { result.push(arr.splice(startIndex, size)); } return result; }
This is how I solved it using do while loop and splice method - function chunk(arr, size) { let givenArr = [...arr]; let result = []; do { result.push(givenArr.splice(0, size)); } while (givenArr.length > 0); return result; }
Incredibly informative and engaging Interview Series! You’ve made a complex interview topic so easy to understand with clear explanation. This is exactly the kind of interview content we need more of. Great job Sir! 🧠💡
I think for the first problem(chunk), the correct comparison would be that the milkman is washing the jar with water every time he pours the milk instead of using a new one. And the correct approach would be just to use the same jar without even washing it. Tha last question was amazing🎉
It's really amazing video 😍. I have learnt lot of things from this video.which will help me my upcoming interview.thanks alot chirag sir🙏 . keep posting these type of video. One thing I want to share, I know Prikshit Chawla ,he is my instructor of advance javascript.the way he is teaching is amazing. He is good instructor also❤🥰.
Sir you are a master piece ❤ I have a small request please bring a big project where you will do start things by explaining basics of any feature and we will end by creating that by our own . but please bring something.
this is such a great mock interview, learnt a lot from u, will buy ur courses! First time I want to buy these online courses! Thank you! Plz make more!
Implemented chunk problem using slice: Here is the implementation. const chunk = (arr, size) => { const result = []; for (let i = 0; i < arr.length; ) { result.push(arr.slice(i, i + size)); i += size; } return result; };
Thank you for the Chakde Frontend Interview series! It has been very helpful! 😊 Sir could you please clarify something from Task 1? How is this approach better: result.push([...minAns]); // Copying the content to a new array minAns.length = 0; compared to this approach: result.push(minAns); minAns = []; // Creates a new array for minAns Both seem to clear the array and both create a new array in memory, but in different ways. Could you explain why the first method is considered better than the second one?
Basically you are creating many minAns[] arrays, which basically consuming more ram, If you use minAns.length = 0 You are using same array again and again without re-initializing it. That's y he got empty arrays in results When he made length = 0 Not copying content from new array its copying content from old array and emptying by assigning length 0
the first question led to debate in chat for time and space complexity i have done small research why the approach shown by chirag bhai is good. if we are not altering the value of miniAss for the approach of prikshit then that approach is very good, but if we are altering the value which in production we never knows the things go hand in hand - so for that reason the approach of chirag bhai is fine enough.
Array length resetting to 0 makes the array empty was something new. Last i knew was that if we do function.length it gives us the number of arguments in the particular function
For the first question i feel chirag tried to go for over optimisation , Actually whatever the approach prikshit has given is the optimal solution. Here are the reasons why ? 1. spread operator copies the data from one array to another array which takes O(k) TC. 2. Updating the length of the array `arr.length = 0` will internally removes all the elements ( which is again be given to the garbage collector ) and takes an additional O(k) TC though it seems to take constant TC. So the overall TC for chirag's solution would be O( n * k ) where `n` total length of source array and `k` is the chunk size & SC will be O(k) But for the first approach which prikshit has written takes O(n) TC and O(k) SC.
CODE Question 1 :- The approach is to take only 1 variable and use it repeatedly. Time Complexity is O(N) as we need to traverse the whole array. function chunk(arr, size) { if(size >= arr.length) return arr; if(size
Questions: 1. Chunk Approach 1: Using Slice Operation In this approach, we use the `slice` method to create subarrays. const chunk = (arr, size) => { let n = arr.length; const ans = [];
for (let i = 0; i < n; i += size) { ans.push(arr.slice(i, i + size)); }
return ans; } let arr = [1, 2, 3, 4, 5]; // Size = 1 let size = 1; let res = chunk(arr, size); console.log(res); // [[1], [2], [3], [4], [5]] // Size = 2 size = 2; res = chunk(arr, size); console.log(res); // [[1, 2], [3, 4], [5]] // Size = 3 size = 3; res = chunk(arr, size); console.log(res); // [[1, 2, 3], [4, 5]] Approach 2: Iterating Through the Array and Adding Chunks One by One In this approach, we iterate through the array and build chunks manually. const chunk = (arr, size) => { const ans = []; let chunk = []; for (let i = 0; i < arr.length; i++) { chunk.push(arr[i]); if (chunk.length === size || i === arr.length - 1) { ans.push([...chunk]); chunk.length = 0; } } return ans; } let arr = [1, 2, 3, 4, 5]; // Size = 1 let size = 1; let res = chunk(arr, size); console.log(res); // [[1], [2], [3], [4], [5]] // Size = 2 size = 2; res = chunk(arr, size); console.log(res); // [[1, 2], [3, 4], [5]] // Size = 3 size = 3; res = chunk(arr, size); console.log(res); // [[1, 2, 3], [4, 5]]
This approach is dependent on slice method, in C lang, it will push garbage value at the last chunk, So do this:::: const input =[1,2,3,4,7] const Chunk=(arr = input, size =1)=>{ let result =[] for(let i = 0 ; i < arr.length; i=i+size){ console.log(i,i+size,arr.length) if(i+size >= arr.length){ result.push(arr.slice(i,arr.length)) } else{ result.push(arr.slice(i,i+size)) } } return result } console.log(Chunk(input, 3))
Using Splice which modifies the original arr and helps to easily cut out the portion and add it to and:- var chunk = function (arr, size) { const result = []; while (arr.length > 0) { const portion = arr.splice(0, size); result.push(portion); } return result; };
1. array chunking my solution: function chunk(arr,chunkSize){ let result = [] while(arr.length>chunkSize){ result.push(arr.splice(0,chunkSize)) arr.toSpliced(0,chunkSize) } result.push(arr) return result }
Question 2 //without abort controller function debouncing(fnc, delay) { let timer; let firstTime = true; let latestRequestId = 0; return function (...args) { latestRequestId++; // Increment the counter for each call const currentRequestId = latestRequestId; // Store the current request id if (firstTime) { fnc(...args).then((response) => { // Only process the response if it belongs to the latest request if (currentRequestId === latestRequestId) { console.log(response); } }); firstTime = false; } else { if (timer) { // fnc(...args); clearTimeout(timer); } timer = setTimeout(() => { fnc(...args).then((response) => { // Only process the response if it belongs to the latest request if (currentRequestId === latestRequestId) { console.log(response); } }); }, delay); } }; } function print(data) { return new Promise((resolve) => { // Simulate variable delay in API response const randomDelay = Math.floor(Math.random() * 10) + 1; // Random delay between 1ms to 10ms setTimeout(() => { resolve(`API Response for: ${data} (after ${randomDelay}ms)`); }, randomDelay); }); } let searchTerm = debouncing(print, 1000); //case 1: for the first time the default data should show searchTerm("I"); searchTerm("Ip"); searchTerm("Iph"); searchTerm("Ipho"); //with AbortController function debouncing(fnc, delay) { let timer; let firstTime = true; let controller = new AbortController(); return function (...args) { if (firstTime) { controller = new AbortController(); fnc(...args, controller.signal).then((response) => { console.log(response); }); firstTime = false; } else { if (timer) { // fnc(...args); clearTimeout(timer); } timer = setTimeout(() => { controller.abort(); controller = new AbortController(); // Create a new controller for the new request fnc(...args, controller.signal).then((response) => { console.log(response); }); }, delay); } }; } function print(data, signal) { return new Promise((resolve) => { // Simulate variable delay in API response const randomDelay = Math.floor(Math.random() * 10) + 1; // Random delay between 1ms to 10ms setTimeout(() => { if (signal.aborted) { reject(new DOMException("Aborted", "AbortError")); } else { resolve(`API Response for: ${data} (after ${randomDelay}ms)`); } }, randomDelay); }); } let searchTerm = debouncing(print, 1000); //case 1: for the first time the default data should show searchTerm("I"); searchTerm("Ip"); searchTerm("Iph"); searchTerm("Ipho");
➡️➡️Using Splice which modifies the original arr and helps to easily cut out the portion and add it to result- var chunk = function (arr, size) { const result = []; while (arr.length > 0) { const portion = arr.splice(0, size); result.push(portion); } return result; };
let countValue= 0; // define function let count = () => { countValue += 1; console.log("Count Value after increment: " + countValue); // Define and attach the reset function inside the count function count.reset = () => { countValue = 0; console.log("Count Value after reset: " + countValue); } } count(); count(); count(); count.reset(); that approch is simple and best i think
is that it will work here 😅 sorry let i = 1; function count(){ console.log(i++); return { reset:function(){ i = 0; } } } count(); count(); count().reset(); count(); count(); count(); count();
question 1 ) best way of writing code function divide(chunk, size){ let res = []; while(chunk.length > size){ res.push(chunk.splice(0,size)); } if(chunk.length) res.push(chunk) return res }
This should do it const chunk = (array, size) => { const chunkedArray = []; for (let i = 0; i < array.length; i += size) { chunkedArray.push(array.slice(i, i + size)); } return chunkedArray; };
I dont know for 1st question why he didn't used the array method of slice. Here's an example for the same var calculated = [] function chuncking(arr,length) { let newArr = [...arr] if(!newArr.length){ return calculated } else { console.log(newArr) let SubArr = newArr.slice(0,length) calculated.push(SubArr) chuncking(newArr.slice(length), length) } } chuncking([1,2,3,4,5,6,7,8,9],2) console.log(calculated) Although I don't expect an 1 year experienced to give this answer but comment section is also using for loop for this. If javascript gave an method for this task why use an for loop for this.
Is these correct way of doing ? function myCount() { let i = 0; function innerCount() { i++; console.log(i) } innerCount.reset = function() { i=0; } return innerCount; } const count = myCount();
function chunk(arr, size) { let tempArr = []; for (let i = 0; i < arr.length; i = i + size) { tempArr.push(arr.slice(i, size + i)); } console.log(tempArr); } My solution to the first question
For count function task may be we can assign reset and count as a property of countFn using dot operator. Example: function countFn() { countFn.count += 1; return countFn.count; } countFn.count = 0; countFn.reset = () => { countFn.count = 0; }
I have one doubt in debouncing problem if anyone can answer that. When declaring variable id or first inside debounce function, will it not create a new copy every time debounce is called. How can we remember the old ID or whether it is a first keystroke or not?? @engineerchirag
Solution for question 2: ``` // debounce method const debounce = (cb: Function, delay: number) => { let timer: number | undefined; let isFirstCall = true; return (...args: any[]) => { clearTimeout(timer); timer = setTimeout(() => { cb(...args); }, delay); // set the timer to undefined so that the timer for the first call isn't cleared if (isFirstCall) { timer = undefined; } isFirstCall = false; }; }; ```
// please implement your chunk(arr:any[],size:number) function chunk(arry=[],size){ let anotherArray = [] while (arry.length>0) { let smallArray = arry.splice(0,size) anotherArray.push(smallArray) } return anotherArray } console.log(chunk([1,2,3,4,5],1)) console.log(chunk([1,2,3,4,5],2)) console.log(chunk([1,2,3,4,5],3)) console.log(chunk([1,2,3,4,5],4)) console.log(chunk([1,2,3,4,5],5)) this is my answer
this is also working.... let i = 0; function foo(){ console.log(i++); } foo.reset = function (){ i = 0; } foo(); foo(); foo(); foo.reset(); foo(); foo(); foo(); foo();
function deBounce(typing, delay, ...args) { setTimeout(() => { console.log(`Executing typing with args: ${args}`); typing(...args); }, delay); } function typing(a) { console.log(a); } // Calls that will now not overwrite each other deBounce(typing, 2000, "y"); deBounce(typing, 3000, "ya"); deBounce(typing, 100, "yas"); deBounce(typing, 0, "yash");
function chunk(arr, size){ let res = [] let min = [] arr.forEach((item, idx)=>{ if(min.length < size){ min.push(item) }else{ res.push(min) min = [item] } }) res.push(min) return res } console.log(chunk([1,2,3,4,5], 4)) not solved coding problem from last 1 year and after solving this problem, before the candidate now i feel like i am still worthy. 😛 thanks for the video @engineerchirag const count = (() =>{ let c = 0 return function (){ c++ return c } })() count.reset = () =>{ c = 0 return 0 } console.log(count()) console.log(count()) console.log(count.reset())
Your videos are really brainstorming every time it is one level up , the way debounce can be asked and the scenarios that you asked helps a lot.
❤️
For first one:
function chunkArray(arr, chunkSize) {
let map = {};
let i = 0;
if (chunkSize < 0) throw new Error("Chunk side should be greater than 0");
if (chunkSize >= arr.length) return [arr];
while (i < arr.length) {
let currentChunk = arr.slice(i, Math.min(i + chunkSize, arr.length));
map[i.toString()] = currentChunk;
i += chunkSize;
}
return Object.values(map);
}
The interview was very informative. The candidate's technical skills and grasp of JavaScript concepts were particularly impressive.
All the questions are amazing. Solved Chunk problem using splice.
function chunk(arr, size) {
if (size > arr.length) {
return [arr];
}
let count = Math.ceil(arr.length/size), result = [], startIndex = 0;
for(let i = 0; i < count; i ++) {
result.push(arr.splice(startIndex, size));
}
return result;
}
This is how I solved it using do while loop and splice method -
function chunk(arr, size) {
let givenArr = [...arr];
let result = [];
do {
result.push(givenArr.splice(0, size));
} while (givenArr.length > 0);
return result;
}
The last question was really interesting. Learnt many new things!
❣️
Incredibly informative and engaging Interview Series! You’ve made a complex interview topic so easy to understand with clear explanation. This is exactly the kind of interview content we need more of. Great job Sir! 🧠💡
Glad you enjoyed it! ❤️
Every Video Of Chakde frontend Is A Gem for Us
Thanks a lot Sir ❤❤❤❤
❤️
Please keep posting more videos. It really helps. Thank a lot
I think for the first problem(chunk), the correct comparison would be that the milkman is washing the jar with water every time he pours the milk instead of using a new one. And the correct approach would be just to use the same jar without even washing it.
Tha last question was amazing🎉
Nice video. Please keep posting such interview videos
It's really amazing video 😍. I have learnt lot of things from this video.which will help me my upcoming interview.thanks alot chirag sir🙏 . keep posting these type of video.
One thing I want to share, I know Prikshit Chawla ,he is my instructor of advance javascript.the way he is teaching is amazing. He is good instructor also❤🥰.
Glad it was helpful! ❤️
For the first question. my solution is.
const chunk = (arr, size) => {
const result = [];
for(let i=0; i< arr.length / size; i++){
const chunked = arr.slice(i * size, (i+ 1) * size)
result.push(chunked);
}
console.log(result)
}
Sir you are a master piece ❤ I have a small request please bring a big project where you will do start things by explaining basics of any feature and we will end by creating that by our own . but please bring something.
Good idea 😊
Quality questions
this is such a great mock interview, learnt a lot from u, will buy ur courses! First time I want to buy these online courses! Thank you! Plz make more!
Awesome, thank you! ❤️❤️ That means a lot to me 🙏
Thanks, I am learning lots of programing trick and solutions to your this series
Great to hear!
Implemented chunk problem using slice:
Here is the implementation.
const chunk = (arr, size) => {
const result = [];
for (let i = 0; i < arr.length; ) {
result.push(arr.slice(i, i + size));
i += size;
}
return result;
};
1.In this way we can also do the 1st question.
function chunk(arr,size){
let result=[];
let i=0;
while(i
What if arr[i] become 0 at any point then it will not work, 🤔
These questions were quite a thinker!
❤️
Thank you for the Chakde Frontend Interview series! It has been very helpful! 😊
Sir could you please clarify something from Task 1?
How is this approach better:
result.push([...minAns]); // Copying the content to a new array
minAns.length = 0;
compared to this approach:
result.push(minAns);
minAns = []; // Creates a new array for minAns
Both seem to clear the array and both create a new array in memory, but in different ways. Could you explain why the first method is considered better than the second one?
Basically you are creating many minAns[] arrays, which basically consuming more ram,
If you use minAns.length = 0
You are using same array again and again without re-initializing it.
That's y he got empty arrays in results
When he made length = 0
Not copying content from new array its copying content from old array and emptying by assigning length 0
the first question led to debate in chat for time and space complexity
i have done small research why the approach shown by chirag bhai is good.
if we are not altering the value of miniAss for the approach of prikshit then that approach is very good,
but if we are altering the value which in production we never knows the things go hand in hand - so for that reason the approach of chirag bhai is fine enough.
Array length resetting to 0 makes the array empty was something new. Last i knew was that if we do function.length it gives us the number of arguments in the particular function
The modified debounce question is really nice
For the first question i feel chirag tried to go for over optimisation , Actually whatever the approach prikshit has given is the optimal solution.
Here are the reasons why ?
1. spread operator copies the data from one array to another array which takes O(k) TC.
2. Updating the length of the array `arr.length = 0` will internally removes all the elements ( which is again be given to the garbage collector ) and takes an additional O(k) TC though it seems to take constant TC.
So the overall TC for chirag's solution would be O( n * k ) where `n` total length of source array and `k` is the chunk size & SC will be O(k)
But for the first approach which prikshit has written takes O(n) TC and O(k) SC.
I realised this after interview. Couldn't think of it during interview because of recording factor nervousness. 😅
Thank you Chirag for having me on your channel!
bro from where did you practice JS interview based questions?
@@rishabsharma5307
Leetcode JS
GreatFrontend
My pleasure ❤️
Congrats sir🎉
Befor watching this video i didn't know how garbage collector work but after the first question i understand thanks chirag
❤️
@amandubey4412 Do you mind sharinng it here what u got to know about GC?
Lot's of high level concepts in your interviews......keep this but keep something for freshers also
Many more episodes to come 🚀
Great video please do more such video for the beginners
More to come! ❤️
CODE Question 1 :- The approach is to take only 1 variable and use it repeatedly. Time Complexity is O(N) as we need to traverse the whole array.
function chunk(arr, size) {
if(size >= arr.length) return arr;
if(size
Questions:
1. Chunk
Approach 1: Using Slice Operation
In this approach, we use the `slice` method to create subarrays.
const chunk = (arr, size) => {
let n = arr.length;
const ans = [];
for (let i = 0; i < n; i += size) {
ans.push(arr.slice(i, i + size));
}
return ans;
}
let arr = [1, 2, 3, 4, 5];
// Size = 1
let size = 1;
let res = chunk(arr, size);
console.log(res); // [[1], [2], [3], [4], [5]]
// Size = 2
size = 2;
res = chunk(arr, size);
console.log(res); // [[1, 2], [3, 4], [5]]
// Size = 3
size = 3;
res = chunk(arr, size);
console.log(res); // [[1, 2, 3], [4, 5]]
Approach 2: Iterating Through the Array and Adding Chunks One by One
In this approach, we iterate through the array and build chunks manually.
const chunk = (arr, size) => {
const ans = [];
let chunk = [];
for (let i = 0; i < arr.length; i++) {
chunk.push(arr[i]);
if (chunk.length === size || i === arr.length - 1) {
ans.push([...chunk]);
chunk.length = 0;
}
}
return ans;
}
let arr = [1, 2, 3, 4, 5];
// Size = 1
let size = 1;
let res = chunk(arr, size);
console.log(res); // [[1], [2], [3], [4], [5]]
// Size = 2
size = 2;
res = chunk(arr, size);
console.log(res); // [[1, 2], [3, 4], [5]]
// Size = 3
size = 3;
res = chunk(arr, size);
console.log(res); // [[1, 2, 3], [4, 5]]
First approach was simple and easy to understand
1 approach is from chatgpt😂
This approach is dependent on slice method, in C lang, it will push garbage value at the last chunk,
So do this::::
const input =[1,2,3,4,7]
const Chunk=(arr = input, size =1)=>{
let result =[]
for(let i = 0 ; i < arr.length; i=i+size){
console.log(i,i+size,arr.length)
if(i+size >= arr.length){
result.push(arr.slice(i,arr.length))
}
else{
result.push(arr.slice(i,i+size))
}
}
return result
}
console.log(Chunk(input, 3))
Using Splice which modifies the original arr and helps to easily cut out the portion and add it to and:-
var chunk = function (arr, size) {
const result = [];
while (arr.length > 0) {
const portion = arr.splice(0, size);
result.push(portion);
}
return result;
};
1. array chunking
my solution:
function chunk(arr,chunkSize){
let result = []
while(arr.length>chunkSize){
result.push(arr.splice(0,chunkSize))
arr.toSpliced(0,chunkSize)
}
result.push(arr)
return result
}
Valuable Content ❤
❤️
Question 2
//without abort controller
function debouncing(fnc, delay) {
let timer;
let firstTime = true;
let latestRequestId = 0;
return function (...args) {
latestRequestId++; // Increment the counter for each call
const currentRequestId = latestRequestId; // Store the current request id
if (firstTime) {
fnc(...args).then((response) => {
// Only process the response if it belongs to the latest request
if (currentRequestId === latestRequestId) {
console.log(response);
}
});
firstTime = false;
} else {
if (timer) {
// fnc(...args);
clearTimeout(timer);
}
timer = setTimeout(() => {
fnc(...args).then((response) => {
// Only process the response if it belongs to the latest request
if (currentRequestId === latestRequestId) {
console.log(response);
}
});
}, delay);
}
};
}
function print(data) {
return new Promise((resolve) => {
// Simulate variable delay in API response
const randomDelay = Math.floor(Math.random() * 10) + 1; // Random delay between 1ms to 10ms
setTimeout(() => {
resolve(`API Response for: ${data} (after ${randomDelay}ms)`);
}, randomDelay);
});
}
let searchTerm = debouncing(print, 1000);
//case 1: for the first time the default data should show
searchTerm("I");
searchTerm("Ip");
searchTerm("Iph");
searchTerm("Ipho");
//with AbortController
function debouncing(fnc, delay) {
let timer;
let firstTime = true;
let controller = new AbortController();
return function (...args) {
if (firstTime) {
controller = new AbortController();
fnc(...args, controller.signal).then((response) => {
console.log(response);
});
firstTime = false;
} else {
if (timer) {
// fnc(...args);
clearTimeout(timer);
}
timer = setTimeout(() => {
controller.abort();
controller = new AbortController(); // Create a new controller for the new request
fnc(...args, controller.signal).then((response) => {
console.log(response);
});
}, delay);
}
};
}
function print(data, signal) {
return new Promise((resolve) => {
// Simulate variable delay in API response
const randomDelay = Math.floor(Math.random() * 10) + 1; // Random delay between 1ms to 10ms
setTimeout(() => {
if (signal.aborted) {
reject(new DOMException("Aborted", "AbortError"));
} else {
resolve(`API Response for: ${data} (after ${randomDelay}ms)`);
}
}, randomDelay);
});
}
let searchTerm = debouncing(print, 1000);
//case 1: for the first time the default data should show
searchTerm("I");
searchTerm("Ip");
searchTerm("Iph");
searchTerm("Ipho");
function chunk(arr,size){
let result = []
let temp = []
let count =0
for(let i =0; i0){
result.push(temp)
}
return result
}
Question 1 Solution
function chunk(array, size) {
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
console.log(chunk([1, 2, 3, 4, 5], 1));
console.log(chunk([1, 2, 3, 4, 5], 3));
function chunk(arr, size) {
let result = [];
for (let i = 0; i < arr.length; i = i + size) {
result.push(arr.slice(i, i + size));
}
return result;
}
So help me with something, once the miniAns is pushed in result array, why would the GC GC it?
Tysm for this interview sir ❤❤
My pleasure ❤️
First comment, we want more videos like this .
More to come! ❤️
Doing great chirag 💯 💯 🎉
❤️
➡️➡️Using Splice which modifies the original arr and helps to easily cut out the portion and add it to result-
var chunk = function (arr, size) {
const result = [];
while (arr.length > 0) {
const portion = arr.splice(0, size);
result.push(portion);
}
return result;
};
let countValue= 0;
// define function
let count = () => {
countValue += 1;
console.log("Count Value after increment: " + countValue);
// Define and attach the reset function inside the count function
count.reset = () => {
countValue = 0;
console.log("Count Value after reset: " + countValue);
}
}
count();
count();
count();
count.reset();
that approch is simple and best i think
is that it will work here 😅 sorry
let i = 1;
function count(){
console.log(i++);
return {
reset:function(){
i = 0;
}
}
}
count();
count();
count().reset();
count();
count();
count();
count();
question 1 ) best way of writing code
function divide(chunk, size){
let res = [];
while(chunk.length > size){
res.push(chunk.splice(0,size));
}
if(chunk.length) res.push(chunk)
return res
}
question 3)
function createCount() {
let counter = 0;
const count = () => {
counter++;
return counter;
};
count.reset = () => {
counter = 0;
};
return count;
}
// Usage:
const count = createCount();
console.log(count()); // 1
console.log(count()); // 2
console.log(count()); // 3
count.reset(); // Reset the counter
console.log(count()); // 1
console.log(count()); // 2
console.log(count()); // 3
Can anyone please tell me what code editor are they using ?
Counter problem:
function countFunction() {
this.value +=1
return this.value
}
const context = {
value: 0,
}
const count = countFunction.bind(context);
count.reset = function () {
this.value = 0
}.bind(context)
Chunking problem:
const chunk = (arr, size) => {
if(arr.length
This should do it
const chunk = (array, size) => {
const chunkedArray = [];
for (let i = 0; i < array.length; i += size) {
chunkedArray.push(array.slice(i, i + size));
}
return chunkedArray;
};
I believe he comes from a CP background, and doesn't know JS in depth
In the last question why the arrow function rather then normal function??
This is very helpful.
I see this count(), count.reset() in libraries like jest.
Thanks 🙏
function fun(arr, size){
const result = (curSize)=>{
if(curSize < arr.length){
console.log(arr.slice(curSize, curSize +size))
result(curSize+size)
}
}
return result(0)
}
let counter = 0;
function count(){
return counter += 1;
}
count.reset = function(){
counter = 0;
}
count(); // 1
count(); // 2
count.reset(); // 0
count(); // 1
count(); // 2
count(); // 3
console.log(counter); // 3 Thoughts please?
I dont know for 1st question why he didn't used the array method of slice. Here's an example for the same
var calculated = []
function chuncking(arr,length) {
let newArr = [...arr]
if(!newArr.length){
return calculated
} else {
console.log(newArr)
let SubArr = newArr.slice(0,length)
calculated.push(SubArr)
chuncking(newArr.slice(length), length)
}
}
chuncking([1,2,3,4,5,6,7,8,9],2)
console.log(calculated)
Although I don't expect an 1 year experienced to give this answer but comment section is also using for loop for this. If javascript gave an method for this task why use an for loop for this.
Hi Chirag could you please suggest from where we can find and prepare these type of questions. It will really helpful for us. Thanks in advance
Chakde Frontend Interviews series 😛
Is these correct way of doing ?
function myCount() {
let i = 0;
function innerCount() {
i++;
console.log(i)
}
innerCount.reset = function() {
i=0;
}
return innerCount;
}
const count = myCount();
( my Approach -> using pointer )function chunking(arr, chunk) {
let result = [];
let pointer = 0;
for (let i = 0; i < arr.length; i++) {
result[pointer] !== undefined
? result[pointer].push(arr[i])
: (result[pointer] = [arr[i]]);
if (result[pointer].length === chunk) {
pointer++;
}
}
return result;
}
console.log(chunking([1, 2, 3, 4, 5], 1));
console.log(chunking([1, 2, 3, 4, 5], 2));
console.log(chunking([1, 2, 3, 4, 5], 3));
console.log(chunking([1, 2, 3, 4, 5], 4));
console.log(chunking([1, 2, 3, 4, 5], 5));
@Chirag Its Beauty..
❤️
Chirag please suggest me best js dsa paid or free any?
function chunk(arr, size) {
let tempArr = [];
for (let i = 0; i < arr.length; i = i + size) {
tempArr.push(arr.slice(i, size + i));
}
console.log(tempArr);
}
My solution to the first question
function chunk(arr, size) {
return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
arr.slice(i * size, i * size + size)
);
}
Wallmart my dream company
Achaaaa. you will make it bro😄
More such interviews 😜
Many more in pipeline 🚀
@@engineerchirag amazing 🤞🏻❣️
For count function task may be we can assign reset and count as a property of countFn using dot operator.
Example:
function countFn() {
countFn.count += 1;
return countFn.count;
}
countFn.count = 0;
countFn.reset = () => {
countFn.count = 0;
}
could we use this ◦•●◉✿keyword in the last question✿◉●•◦
learned a lot from the problem you ask...Prikshit Selected
❤️
For 1st question I've followed this approach:
const arr = [1,2,3,4,5];
function chunk(arr, size) {
let newArr = [];
return arr.reduce((ac,cur,i) => {
newArr = [...newArr,cur];
if(newArr.length === size || i===arr.length-1) {
ac = [...ac, newArr.splice(0, newArr.length)]
}
return ac;
},[])
}
console.log(chunk(arr, 1))
console.log(chunk(arr, 2))
console.log(chunk(arr, 3))
console.log(chunk(arr, 4))
console.log(chunk(arr, 5))
Brainstorming 🔥
❤️
I have one doubt in debouncing problem if anyone can answer that. When declaring variable id or first inside debounce function, will it not create a new copy every time debounce is called. How can we remember the old ID or whether it is a first keystroke or not??
@engineerchirag
Study closures. We are not invoking debounce function again and again. We are just invoking return function.
❤
❤️❤️
Q1 Please review
function chunk(data, size) {
const update = [];
let row = [];
for (let i = 0; i < data.length; i++) {
row.push(data[i]);
if (row.length === size || i === data.length - 1) {
update.push(row);
row = [];
}
}
return update;
}
1. chunk
const chunck = (arr,size) => {
const chunkedArray = [];
for(let i=0;i< arr.length;i+=size){
const subArr = arr.slice(i, i+size);
chunkedArray.push(subArr)
}
return chunkedArray;
}
Solution for question 1 in typescript:
```
const chunk = (arr: T[], size: number) => {
let itemsArr: T[] = [];
return arr.reduce((acc, item, index) => {
itemsArr.push(item);
if (itemsArr.length === size) {
acc.push([...itemsArr]);
itemsArr.length = 0;
}
if (index === arr.length - 1 && itemsArr.length > 0) {
acc.push(itemsArr);
}
return acc;
}, []);
};
console.log(chunk([1, 2, 3, 4, 5], 3));
```
Solution for question 2:
```
// debounce method
const debounce = (cb: Function, delay: number) => {
let timer: number | undefined;
let isFirstCall = true;
return (...args: any[]) => {
clearTimeout(timer);
timer = setTimeout(() => {
cb(...args);
}, delay);
// set the timer to undefined so that the timer for the first call isn't cleared
if (isFirstCall) {
timer = undefined;
}
isFirstCall = false;
};
};
```
Prikshit sir 🫡
❤️
let arr=[1,2,3,4,5], size=3
function chunk(arr:any[],size:number){
let ans=[];
let tempArr=[]
for(let el of arr){
let k= tempArr.length;//0
if(k
// please implement your chunk(arr:any[],size:number)
function chunk(arry=[],size){
let anotherArray = []
while (arry.length>0) {
let smallArray = arry.splice(0,size)
anotherArray.push(smallArray)
}
return anotherArray
}
console.log(chunk([1,2,3,4,5],1))
console.log(chunk([1,2,3,4,5],2))
console.log(chunk([1,2,3,4,5],3))
console.log(chunk([1,2,3,4,5],4))
console.log(chunk([1,2,3,4,5],5)) this is my answer
this is also working....
let i = 0;
function foo(){
console.log(i++);
}
foo.reset = function (){
i = 0;
}
foo();
foo();
foo();
foo.reset();
foo();
foo();
foo();
foo();
Count Question
function count() {
if (!count.prototype.cnt || count.prototype.cnt === 0) {
count.prototype.cnt = 0;
}
count.prototype.cnt = count.prototype.cnt + 1;
count.reset = () => {
count.prototype.cnt = 0;
return;
};
return count.prototype.cnt;
}
let increCount =1
function count() {
return increCount++
}
count.reset = function (){
increCount = 1
}
console.log(count())
console.log(count())
console.log(count())
count.reset()
console.log(count())
console.log(count())
console.log(count())
function deBounce(typing, delay, ...args) {
setTimeout(() => {
console.log(`Executing typing with args: ${args}`);
typing(...args);
}, delay);
}
function typing(a) {
console.log(a);
}
// Calls that will now not overwrite each other
deBounce(typing, 2000, "y");
deBounce(typing, 3000, "ya");
deBounce(typing, 100, "yas");
deBounce(typing, 0, "yash");
Accio faculty 😂
Awesome questions !!
solution:
/*
chunk([1,2,3,4,5], 1)
[[1],[2],[3],[4],[5]];
*/
function chunk(arr, size) {
let ans = [];
let count = size;
let temp = new Array();
for (let i = 0; i < arr.length; i++) {
temp.push(arr[i]);
count--;
if (count {
searchFn(...args);
},delay);
}
}
function print(data){
console.log(data);
}
let returnFun = debounce(print, 1000);
returnFun("i");
returnFun("ip");
returnFun("iph");
returnFun("ipho");
/* q3 */
const count = (()=>{
let value = 0;
function inner(){
value++;
console.log(value);
return value;
}
inner.reset = function(){
value=0;
}
return inner;
})();
count();//1
count();//2
count();//3
count.reset()//
count();//1
count();//2
count();//3
function chunk(arr, size){
let res = []
let min = []
arr.forEach((item, idx)=>{
if(min.length < size){
min.push(item)
}else{
res.push(min)
min = [item]
}
})
res.push(min)
return res
}
console.log(chunk([1,2,3,4,5], 4))
not solved coding problem from last 1 year and after solving this problem, before the candidate now i feel like i am still worthy. 😛
thanks for the video @engineerchirag
const count = (() =>{
let c = 0
return function (){
c++
return c
}
})()
count.reset = () =>{
c = 0
return 0
}
console.log(count())
console.log(count())
console.log(count.reset())
Bowl le, dudh nikal and usi bowl ko jake rakh ke ayy. Dubara ek neya bowl le.
function chunk(arr,size){
let result = [[]]
for(let i =0; i