UNPKG

@idealic/poker-engine

Version:

Professional poker game engine and hand evaluator with built-in iterator utilities

78 lines 2.31 kB
/** * Functions for creating chunks of elements from an iterable */ import { pubsub } from './lib/pubsub'; /** * Internal implementation of async chunk * * @param input Source iterable to chunk * @param size Size of each chunk */ async function* _chunk(input, size) { if (size <= 0) return; let buffer = []; for await (const value of input) { buffer.push(value); if (buffer.length >= size) { yield buffer; buffer = []; } } // Yield remaining items if any if (buffer.length > 0) { yield buffer; } } /** * Internal implementation of concurrent chunk * * @param input Source iterable to chunk * @param size Size of each chunk * @param concurrency Maximum number of concurrent operations */ function _chunkConcurrently(input, size, concurrency) { const { publish, producing, wait, output, onReadComplete } = pubsub(concurrency); return output({ onStart: async () => { let buffer = []; // Process the input stream without blocking the main loop try { for await (const item of input) { buffer.push(item); if (buffer.length >= size) { if (producing.size >= concurrency) { await wait(); } const chunk = buffer; buffer = []; publish(chunk); } } } finally { // Publish remaining items if any if (buffer.length > 0) { if (producing.size >= concurrency) { await wait(); } await publish(buffer); await new Promise(setImmediate); } onReadComplete(); } }, }); } export function chunk(input, size, concurrency) { if (typeof input === 'number') { return (_input) => chunk(_input, input, size); } else if (concurrency && concurrency > 1) { return _chunkConcurrently(input, size, concurrency || 1); } else { return _chunk(input, size); } } //# sourceMappingURL=chunk.js.map