Last active
July 12, 2017 16:36
-
-
Save kochmaxence/acf4de936144760229da13c96305085c to your computer and use it in GitHub Desktop.
Differences between blocking & non-blocking array reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bigArray = Array.apply(null, Array(4000)).map(Number.prototype.valueOf, 1); | |
let check = setInterval(() => console.log('-'), 0); | |
const result = bigArray.reduce((acc, value, index) => { | |
acc[index] = value; | |
console.log('ITERATION'); | |
return acc; | |
}, {}); | |
setTimeout(() => clearInterval(check), 2); // setTimeout so we delay the clear a little bit otherwise nothing | |
// would be printed | |
//console.log(result); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function arrayReduce(array, iteratorFn, acc) { | |
if (array === null) | |
throw new TypeError('arrayReduce called on null or undefined'); | |
if (typeof iteratorFn !== 'function') | |
throw new TypeError(iteratorFn + ' is not a function'); | |
if (!Array.isArray(array)) | |
throw new TypeError(array + ' is not an array'); | |
if (!array.length && typeof acc === 'undefined') | |
throw new TypeError('Reduce of empty array with no initial value'); | |
const _acc = typeof acc !== 'undefined' ? acc : array[0]; | |
return new Promise((resolve, reject) => { | |
const iterator = (index, accumulator) => { | |
if (index === array.length) | |
return resolve(accumulator); | |
setImmediate(() => { | |
iteratorFn(acc, array[index], (err, value) => { | |
console.log('ITERATION'); | |
if (err) | |
return reject(err); | |
iterator(index + 1, value); | |
}, index, array); | |
}); | |
} | |
iterator(0, _acc); | |
}); | |
} | |
let check; | |
const bigArray = Array.apply(null, Array(4000)).map(Number.prototype.valueOf, 1); | |
Promise.resolve().then(() => { | |
check = setInterval(() => console.log('-'), 1); | |
}).then(() => { | |
return arrayReduce(bigArray, (acc, value, next, index, original) => { | |
acc[index] = value; | |
next(null, acc); | |
}, {}) | |
}).then(result => { | |
clearInterval(check); | |
//console.log(result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment