Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created February 3, 2017 11:20
Show Gist options
  • Save yowcow/dd612f12029fe02270d088e34b666b4f to your computer and use it in GitHub Desktop.
Save yowcow/dd612f12029fe02270d088e34b666b4f to your computer and use it in GitHub Desktop.
Square a set of numbers at a time
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