// site-async.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

class SiteAsync {

  static each (sourceItems, callback, concurrent = 1) {
    if (!Array.isArray(sourceItems)) {
      throw new Error('each requires an array of objects to be processed');
    }
    if (sourceItems.length === 0) {
      return Promise.resolve();
    }

    var items = sourceItems.slice();
    var running = 0;

    return new Promise((resolve, reject) => {
      function next ( ) {
        let item = items.shift();
        if (!item) {
          return;
        }
        ++running;
        callback(item).then(next).catch(reject).finally(( ) => {
          if (--running === 0) {
            resolve();
          }
        });
      }
      while (concurrent && items.length) {
        next();
        --concurrent;
      }
    });
  }
}

module.exports.SiteAsync = SiteAsync;