import { SEMAPHORE } from "@thi.ng/api/api";
import { __iter, iterator } from "./iterator.js";
import { isReduced } from "./reduced.js";
function partitionBy(...args) {
  return __iter(partitionBy, args, iterator) || (([init, complete, reduce]) => {
    const fn = args[0];
    const f = args[1] === true ? fn() : fn;
    let prev = SEMAPHORE;
    let chunk;
    return [
      init,
      (acc) => {
        if (chunk && chunk.length) {
          acc = reduce(acc, chunk);
          chunk = null;
        }
        return complete(acc);
      },
      (acc, x) => {
        const curr = f(x);
        if (prev === SEMAPHORE) {
          prev = curr;
          chunk = [x];
        } else if (curr === prev) {
          chunk.push(x);
        } else {
          chunk && (acc = reduce(acc, chunk));
          chunk = isReduced(acc) ? null : [x];
          prev = curr;
        }
        return acc;
      }
    ];
  });
}
export {
  partitionBy
};
