Functional Weave
Code in Rust

charts.palette@1.0.0

impl/typescript.ts

1,184 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { PALETTES } from "./charts_palette_data.ts";  ← this capability’s own data, compiled from data/palettes.json into the same file by fune build

/**
 * The first `count` colours of a named categorical scheme, in its order.
 *
 * A scheme has a fixed number of colours chosen to stay distinguishable to
 * people with colour-vision deficiencies; asking for more is an error unless
 * `cycle` says repeating them is acceptable, because a ninth series silently
 * reusing the first colour is a misleading chart.
 */
export function palette(scheme: string, count: number, cycle: boolean): readonly string[] {
  const colours = PALETTES.filter((c) => c.scheme === scheme)
    .slice()
    .sort((a, b) => a.position - b.position)
    .map((c) => c.hex);
  if (colours.length === 0) throw new RangeError(`unknown palette "${scheme}"; use okabe-ito or tol-bright`);
  if (!Number.isInteger(count) || count < 0) {
    throw new RangeError(`count must be a whole number of at least 0, received ${count}`);
  }
  if (count > colours.length && !cycle) {
    throw new RangeError(`palette "${scheme}" has only ${colours.length} colours; pass cycle to repeat them`);
  }
  const out: string[] = [];
  for (let i = 0; i < count; i++) out.push(colours[i % colours.length]);
  return out;
}