Colore JS

Search documentation

Find a function or jump to a section.
v2.0.1

nearest

nearest finds the closest color in a list of swatches or design tokens. It compares colors in OKLab by default and returns the index, so you can retrieve a label or token name from the original list.

Example

import { colore } from 'colore-js';

const match = colore('#7c3aed').nearest(['#f00', '#7b3ae8', '#0f0']);

match.color.css();            // '#7b3ae8'
match.index;                  // 1
match.distance.toFixed(4);    // '0.0078'

Syntax

colore(target).nearest(
  colors: (ColorInput | Color)[],
  distanceFn?: (first: InternalColor, second: InternalColor) => number
): NearestResult

Parameters

NameTypeDescription
targetColorInputThe color you want to match.
colors(ColorInput | Color)[]A list of at least one candidate.
distanceFn(first: InternalColor, second: InternalColor) => numberOptional comparator. Smaller values win. The default uses OKLab distance and ignores opacity.

Returns

NameTypeDescription
colorColorThe winning candidate as a Color instance.
distancenumberDistance from the target under the chosen measure.
indexnumberZero-based position in the original list. An exact tie keeps the earlier color.

Throws

An Error for an empty list, or a ColorError for invalid color input or a non-array candidate argument.

Match an imported color to a design token

import { colore } from 'colore-js';

const tokens = { inverse: '#fff', ink: '#000', muted: '#767676' };
const keys = Object.keys(tokens);
const token = colore('#777').nearest(Object.values(tokens));

keys[token.index]; // 'muted'