Skip to content
中文

Variant and preference ordering ​

The policy implementation follows.

ts
export function selectVariant<Value>(
  values: readonly Value[],
  options: { previous?: Value; randomIndex(limit: number): number },
): Value | undefined {
  if (!values.length) return undefined;
  const candidates =
    values.length > 1 ? values.filter((value) => value !== options.previous) : [...values];
  const pool = candidates.length ? candidates : [...values];
  if (pool.length === 1) return pool[0];
  const index = options.randomIndex(pool.length);
  if (!Number.isSafeInteger(index) || index < 0 || index >= pool.length)
    throw new TypeError('Invalid variant index');
  return pool[index];
}

export function resolvePreference<Value>(
  candidates: readonly { value: Value; priority: number; order: number }[],
): Value | undefined {
  if (candidates.some((item) => !Number.isFinite(item.priority) || !Number.isFinite(item.order)))
    throw new TypeError('Invalid preference priority');
  return [...candidates].sort(
    (left, right) => right.priority - left.priority || right.order - left.order,
  )[0]?.value;
}

API reference, usage examples and developer guides.