From c723c5aa09234093e113d9e45399e7e00b2b3787 Mon Sep 17 00:00:00 2001 From: Yarchik Date: Wed, 8 Jul 2026 14:27:39 +0100 Subject: [PATCH] fix(nearest): allow returning all colors for a finite count The result count was capped at one below the number of colors, so requesting a count equal to the array length dropped the farthest match. Cap at the array length instead. --- src/nearest.js | 2 +- test/nearest.test.js | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/nearest.js b/src/nearest.js index 76874fcd..6532b513 100644 --- a/src/nearest.js +++ b/src/nearest.js @@ -12,7 +12,7 @@ const nearest = (colors, metric = differenceEuclidean(), accessor = d => d) => { let arr = colors.map((c, idx) => ({ color: accessor(c), i: idx })); return (color, n = 1, τ = Infinity) => { if (isFinite(n)) { - n = Math.max(1, Math.min(n, arr.length - 1)); + n = Math.max(1, Math.min(n, arr.length)); } arr.forEach(c => { diff --git a/test/nearest.test.js b/test/nearest.test.js index cd061bda..2cc2243f 100644 --- a/test/nearest.test.js +++ b/test/nearest.test.js @@ -40,3 +40,13 @@ test('nearest() with accessor', t => { let nearestColors = nearest(names, undefined, name => palette[name]); assert.deepEqual(nearestColors('red', 1), ['Bright Red']); }); + +test('nearest() returns up to all colors', t => { + let palette = ['red', 'green', 'blue', 'yellow', 'purple']; + let nearestColors = nearest(palette); + assert.equal( + nearestColors('orange', palette.length).length, + palette.length, + 'n equal to the number of colors returns all of them' + ); +});