import { binarySearch } from "@thi.ng/arrays/binary-search";
import { __drain } from "./internal/drain.js";
import { __sortOpts } from "./internal/sort-opts.js";
import { __iter, iterator } from "./iterator.js";
function streamSort(...args) {
  const iter = __iter(streamSort, args, iterator);
  if (iter) {
    return iter;
  }
  const { key, compare } = __sortOpts(args[1]);
  const n = args[0];
  return ([init, complete, reduce]) => {
    const buf = [];
    return [
      init,
      __drain(buf, complete, reduce),
      (acc, x) => {
        const idx = binarySearch(buf, x, key, compare);
        buf.splice(idx < 0 ? -(idx + 1) : idx, 0, x);
        if (buf.length === n) {
          acc = reduce(acc, buf.shift());
        }
        return acc;
      }
    ];
  };
}
export {
  streamSort
};
