I'm trying to solve this promise puzzle and I've had 2 questions:
A) I'm wondering why it's returning empty array. What am i doing wrong?
B) How can I implement async reduce?
B) How can I make it return a Async Array instead of empty array?
Note:
Please make use of
.get
method to iterate through the elements and the return value must be a asyncArray (not a regular array)
Code looks like this:
/**
* Async array.
*/
function AsyncArray(arr) {
this._arr = arr;
this.length = arr.length;
}
/**
* Asynchronously get the array item of the
* given index.
* @param {number} index - array index of the desired item
* @param {function} callback - called with the array item
*/
AsyncArray.prototype.get = function get(index, callback) {
setTimeout(callback, 0, this._arr[index]);
};
/**
* Async version of Array.prototype.map.
* @param {AsyncArray} arr
* @param {function} fn - (item: any) => any
* @returns {Promise<AsyncArray>}
*/
function asyncMap(arr, fn) {
let counter = 0; // counter
const res = []; /// array of promises.
const len = arr.length;
// Get the length.
return new Promise((resolve, reject) => { // Pending.
while(true) {
if(counter===len) {
console.log("before break", res);
break;
}
arr.get(counter, item => {
res[counter] = function() {
return new Promise((resolve, reject) => {
return resolve(fn(item));
});
}();
console.log('r',res);
});
counter += 1;
}
Promise.all(res).then((r1, rej) => {
console.log("hello world", r1);
return resolve(res);
});
});
}
/**
* Async version of Array.prototype.reduce.
* @param {AsyncArray} arr
* @param {function} fn - (val: any, item: any) => any
* @returns {Promise<any>}
*/
function asyncReduce(arr, fn, initVal) {}
const arr = new AsyncArray([1, 2, 3]);
// arr.get(1, item => console.log(item)); // Existing
// Expected result: [2, 4, 6];
asyncMap(arr, x => x * 2).then(arr_ => console.log('asyncMap:', arr_));
// Expected result: 106
// asyncReduce(arr, (v, x) => v + x, 100).then(val => console.log('asyncReduce:', val));