Decide how many partitions to create, clamped to every relevant bound.
(units: Unit<T>[], totalWeight: number, opts: PartitionOptions)
| 92 | |
| 93 | /** Decide how many partitions to create, clamped to every relevant bound. */ |
| 94 | function chooseK<T>(units: Unit<T>[], totalWeight: number, opts: PartitionOptions): number { |
| 95 | const u = units.length; |
| 96 | if (u <= 1) return u; // 0 → 0, 1 → 1 |
| 97 | const ceiling = Math.max(1, Math.floor(opts.concurrencyCeiling ?? 16)); |
| 98 | const minUnits = Math.max(1, Math.floor(opts.minUnitsPerPartition ?? 1)); |
| 99 | |
| 100 | let k: number; |
| 101 | if (opts.maxPartitions !== undefined) { |
| 102 | k = Math.floor(opts.maxPartitions); |
| 103 | } else if (opts.targetWeightPerPartition && opts.targetWeightPerPartition > 0) { |
| 104 | k = Math.ceil(totalWeight / opts.targetWeightPerPartition); |
| 105 | } else { |
| 106 | k = ceiling; // default: spread as wide as the ceiling allows |
| 107 | } |
| 108 | |
| 109 | // Never more partitions than units, than the ceiling, or than minUnits permits. |
| 110 | k = Math.min(k, u, ceiling, Math.max(1, Math.floor(u / minUnits))); |
| 111 | return Math.max(1, k); |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Partition `items` into balanced, non-overlapping groups. |