var message = "I like apple and sunny and crazy bannaas ... and lovey cats";
var getMsgOneCharATime = function(cb, idx) {
// Fetches a character from the message. Simulates an API call by adding a delay to the request.
const apiDelay = 10;
setTimeout(function() {
cb(message[idx]);
}, apiDelay);
};
//// only after following line I can edit!
var countDistinctAsyncWords = function() {
const messageArray = [];
let currentIndex = 0;
function getPromisedCounter(value) {
return new Promise((resolve, reject) => {
if (!value) {
resolve({
value,
index
});
} else {
reject('there is a error');
}
});
}
var counter = setInterval(() => {
getMsgOneCharATime(getPromisedCounter, currentIndex);
currentIndex ++;
});
function saveWord(word) {
if (!word) clearInterval(counter);
console.log(word);
messageArray.push(word);
}
console.log(messageArray);
return messageArray.join();
}
console.log('---');
console.log(countDistinctAsyncWords());
console.log('---end-');
The purpose is to use countDistinctAsyncWords
to print out the message
that got fetched by the fake timeout api getMsgOneCharATime
calling. I still not able to come out an idea how should I intercept each character correctly, assuming that the message
can be infinity and I do not know the length of it. I am also open to other solutions.
Thanks!