Skip to content

Commit af065c8

Browse files
committed
Refactor rgbTo256Color
1 parent f751a43 commit af065c8

1 file changed

Lines changed: 16 additions & 16 deletions

File tree

cli/node.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,21 @@ const ASCII_CHARS =
277277
"█▓▒░@#B8&WM%*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
278278
// cSpell: enable
279279

280+
const CUBE_VALUES = [0, 95, 135, 175, 215, 255];
281+
282+
const findClosestIndex = (value: number): number => {
283+
let minDiff = Infinity;
284+
let closestIndex = 0;
285+
for (let idx = 0; idx < CUBE_VALUES.length; idx++) {
286+
const diff = Math.abs(value - CUBE_VALUES[idx]);
287+
if (diff < minDiff) {
288+
minDiff = diff;
289+
closestIndex = idx;
290+
}
291+
}
292+
return closestIndex;
293+
};
294+
280295
export function rgbTo256Color(r: number, g: number, b: number): number {
281296
// Check if it's a grayscale color first (when all RGB values are very close)
282297
const gray = Math.round((r + g + b) / 3);
@@ -285,8 +300,7 @@ export function rgbTo256Color(r: number, g: number, b: number): number {
285300

286301
// Handle grayscale colors (colors 232-255) - but exclude exact cube values
287302
if (isGrayscale) {
288-
const cubeValues = [0, 95, 135, 175, 215, 255];
289-
const isExactCubeValue = cubeValues.includes(r) && r === g && g === b;
303+
const isExactCubeValue = CUBE_VALUES.includes(r) && r === g && g === b;
290304

291305
if (!isExactCubeValue) {
292306
if (gray < 8) return 232; // Darkest grayscale
@@ -301,20 +315,6 @@ export function rgbTo256Color(r: number, g: number, b: number): number {
301315

302316
// Handle RGB colors (colors 16-231)
303317
// XTerm 256 color cube values: [0, 95, 135, 175, 215, 255]
304-
const cubeValues = [0, 95, 135, 175, 215, 255];
305-
306-
const findClosestIndex = (value: number): number => {
307-
let minDiff = Infinity;
308-
let closestIndex = 0;
309-
for (let i = 0; i < cubeValues.length; i++) {
310-
const diff = Math.abs(value - cubeValues[i]);
311-
if (diff < minDiff) {
312-
minDiff = diff;
313-
closestIndex = i;
314-
}
315-
}
316-
return closestIndex;
317-
};
318318

319319
const r6 = findClosestIndex(r);
320320
const g6 = findClosestIndex(g);

0 commit comments

Comments
 (0)