@@ -188,9 +188,39 @@ export function extractPalette(
188188 } ) ;
189189 }
190190
191- // OKLCH quantization path
192191 let quantized : Array < { color : [ number , number , number ] ; population : number } > ;
193- if ( opts . colorSpace === 'oklch' ) {
192+
193+ // Short-circuit check: collect up to opts.colorCount + 1 unique colors
194+ const seenColors = new Set < string > ( ) ;
195+ const uniqueColors : Array < [ number , number , number ] > = [ ] ;
196+
197+ for ( const color of pixelArray ) {
198+ const key = color . join ( ',' ) ;
199+ if ( ! seenColors . has ( key ) ) {
200+ seenColors . add ( key ) ;
201+ uniqueColors . push ( color ) ;
202+
203+ // The image contains more distinct colors than requested,
204+ // so we can stop searching for unique colors as we know we will have to use the quantizer.
205+ if ( uniqueColors . length > opts . colorCount ) break ;
206+ }
207+ }
208+
209+ // If unique colors <= maxColors, return them directly with population counts
210+ if ( uniqueColors . length <= opts . colorCount ) {
211+ // Count populations for unique colors
212+ const countMap = new Map < string , number > ( ) ;
213+ for ( const color of pixelArray ) {
214+ const key = color . join ( ',' ) ;
215+ countMap . set ( key , ( countMap . get ( key ) || 0 ) + 1 ) ;
216+ }
217+ quantized = uniqueColors . map ( ( color ) => ( {
218+ color,
219+ population : countMap . get ( color . join ( ',' ) ) ! ,
220+ } ) ) ;
221+ }
222+ // OKLCH quantization path
223+ else if ( opts . colorSpace === 'oklch' ) {
194224 const scaled = pixelsRgbToOklchScaled ( pixelArray ) ;
195225 quantized = paletteOklchScaledToRgb (
196226 quantizer . quantize ( scaled , opts . colorCount ) ,
0 commit comments