Skip to content

Instantly share code, notes, and snippets.

@asarode
Last active October 11, 2015 02:32
Show Gist options
  • Select an option

  • Save asarode/69b5b3e33f806b6a0323 to your computer and use it in GitHub Desktop.

Select an option

Save asarode/69b5b3e33f806b6a0323 to your computer and use it in GitHub Desktop.

Revisions

  1. asarode created this gist Oct 11, 2015.
    35 changes: 35 additions & 0 deletions parallel.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    'use strict'

    function parallel(tasks, max, done) {
    let running = 0
    let completed = 0
    next()

    function taskCompleted() {
    completed++
    console.log(`finished task #${completed}`)
    if (completed === tasks.length) return done()
    running--
    next()
    }

    function next() {
    while (running < max && completed + max - 1 < tasks.length) spawnNext()
    }

    function spawnNext() {
    tasks[completed](taskCompleted)
    running++
    console.log(`added task, now running: ${running}`)
    }
    }

    function asyncThing(callback) {
    setTimeout(() => {
    callback()
    }, Math.random() * 2500)
    }

    parallel([asyncThing, asyncThing, asyncThing, asyncThing], 3, () => {
    console.log('finished everything!')
    })
    27 changes: 27 additions & 0 deletions queue.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    'use strict'

    function queue(tasks, callback) {
    function process(index) {
    if (index === tasks.length) {
    console.log('queue has finished processing all tasks')
    if (callback) return callback()
    return
    }
    tasks[index](index, err => {
    if (err) console.log('error occured', err)
    process(index + 1)
    })
    }
    process(0)
    }

    function asyncThing(index, callback) {
    setTimeout(() => {
    console.log(`did async thing #${index}`)
    callback(null)
    }, 500)
    }

    const tasks = [asyncThing, asyncThing, asyncThing, asyncThing, asyncThing]

    queue(tasks)