Created
February 3, 2017 11:20
-
-
Save yowcow/dd612f12029fe02270d088e34b666b4f to your computer and use it in GitHub Desktop.
Square a set of numbers at a time
This file contains hidden or 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 sliceTodos = todos => | |
todos.length <= 3 | |
? [todos, []] | |
: [todos.slice(0, 3), todos.slice(3)] | |
const square = (x, callback) => | |
setTimeout(() => callback(x ** 2), 1000) | |
const squarePromise = x => | |
new Promise(resolve => square(x, res => resolve(res))) | |
const squareParallel = todos => { | |
const [currentTodos, nextTodos] = sliceTodos(todos) | |
return Promise.all( | |
currentTodos.map(todo => squarePromise(todo)) | |
) | |
.then(results => { | |
console.log(`Got results for ${currentTodos} => ${results}`) | |
nextTodos.length | |
? squareParallel(nextTodos) | |
: console.log('All items squared!') | |
}) | |
} | |
console.log("==== With 8 elements ====") | |
squareParallel([1, 2, 3, 4, 5, 6, 7, 8]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment