"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = series;

var _setImmediate2 = require("./_setImmediate");

function series(tasks, callback) {
  var length = tasks.length;
  var results = [];
  var i = 0;

  if (length === 0) {
    callback(null, []);
    return;
  }

  run();

  function run() {
    tasks[i++](cb);
  }

  function cb(err, res) {
    results.push(res);
    /* istanbul ignore else */

    if (err || length === i) {
      callback && callback(err, results);
    } else if (i < length) {
      (0, _setImmediate2._setImmediate)(function () {
        // prevent RangeError: Maximum call stack size exceeded for sync tasks
        run();
      });
    }
  }
}