So first of all, I felt so like I didn't give my 100%,
Here is the question:
Write down a function (request with parameters url & calllback) such that you can hit this function multiple times but at one time only 1 callback will be active.
Example I can do something like this:
request(url1, callback1)
request(url2, callback2)
request(url3, callback3)
My response:
// We can have an array and push each url & callback inside inside in this array
// Each time we will have a variable lastExecutedIndex, initially set to -1
// We will also have another variable pendingIndex, initially set to -1
Intuition: We will call this request function, and we will simply put the info in the array and initiate a
recursive helper() function. The job of this recursive helper function will be is to identify whether we have a pending callback (identified by pendingIndex), if so dont do anything, else check whether there is some callback which can be picked up identified by condition array.length > lastExecutedIndex + 1, if so execute it and call itself recursively.
Something like
// Global variables
const arr = [];
let lastExecutedIndex = -1, pendingIndex = 1;
// Request function
function request(url, callback) {
arr.push({ url, callback });
helper();
}
// Helper recursive function
function helper() {
if (pendingIndex != -1) {
return false;
}
if (arr.length <= lastExecutedIndex + 1) {
return false;
}
// Pick next index's url & callback
const { url, callabck } = arr[lastExecutedIndex + 1];
// pendingIndex = lastExecutedIndex + 1;
// Fetch that url
fetch(url, function (err, data) {
// Initiate callback
callback(err, data);
// Update lastExecutedIndex
lastExecutedIndex++;
// Call it recursively if array.length < lastExecutedIndex + 1
if (array.length < lastExecutedIndex + 1) {
helper();
}
});
}
I messed up a bit and lost track of my variables and didn't write it down as cleanly or precisely
Please point out any mistakes or a better way to do this.
Followup: How will we make sure that my state management is intact, for that I again said without thinking properly that we can use Prototype and make a Wrapper class and then when we initiate this class we will have only state management intact as long as we use that particular object or we can also use window object or local storage