{"size": 895, "ext": "js", "max_stars_repo_path": "lib/flow.js", "max_stars_repo_name": "suguru03/aigle", "max_stars_repo_stars_event_min_datetime": "2017-02-13T06:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T01:15:07.000Z", "max_issues_repo_path": "lib/flow.js", "max_issues_repo_name": "suguru03/aigle", "max_issues_repo_issues_event_min_datetime": "2017-02-27T06:27:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-08T17:04:33.000Z", "max_forks_repo_path": "lib/flow.js", "max_forks_repo_name": "suguru03/aigle", "max_forks_repo_forks_event_min_datetime": "2017-02-15T07:43:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-23T20:41:39.000Z"}
{"max_stars_count": 340, "max_issues_count": 123, "max_forks_count": 18, "avg_line_length": 22.375, "max_line_length": 62, "alphanum_fraction": 0.5810055866}
'use strict';

const Aigle = require('./aigle');

module.exports = flow;

/**
 * @param {Function[]} funcs
 * @return {Function} Returns the new composite function
 * @example
 *   const add = (a, b) => Aigle.delay(10, a + b);
 *   const square = n => Aigle.delay(10, n * n);
 *   const addSquare = Aigle.flow(add, square);
 *   return addSquare(1, 2).then(value => {
 *     console.log(value); // 9
 *   });
 */
function flow(...funcs) {
  const [handler = thru, ...handlers] = flatArray(funcs);
  return (...args) =>
    Aigle.resolve(handler(...args)).then((data) =>
      Aigle.reduce(handlers, (acc, func) => func(acc), data)
    );
}

function thru(arg) {
  return arg;
}

function flatArray(args) {
  const l = args.length;
  const array = [];
  let i = -1;
  while (++i < l) {
    const arg = args[i];
    Array.isArray(arg) ? array.push(...arg) : array.push(arg);
  }
  return array;
}
