Skip to content
Logo

T.unique

Builders for values that don't repeat. T.unique is not a kind of its own. Each builder returns an ordinary schema of an existing kind, so T.unique.string.whereby(...) is a string schema everywhere else: its type, .override(), and adapters all treat it as one.

T.object({
  id: T.unique.number.integer.whereby({ min: 1, max: 10_000 }),
  handle: T.unique.string.whereby({ length: 8, composition: { lowercase: 1 } }),
  tags: T.unique
    .array(T.enum.uniform(["new", "sale", "gift", "bulk"]))
    .whereby({ length: { max: 3 } }),
});

Two scopes

There are two kinds of builder, and they don't repeat over different spans.

Leaves never repeat for the life of the built Fabricator. That covers every .fabricate() call on it, and every fabricate(schema) call in one scope. Under the harness integration, each test starts fresh. A new new Fabricator(...) also starts over.

  • T.unique.enum.uniform([...]) and T.unique.enum.weighted([...])
  • T.unique.number, .whereby({ min, max }), .integer, .integer.whereby({ min, max }), and .integer.big, which is T.unique.bigint
  • T.unique.bigint.whereby({ min, max })
  • T.unique.string.whereby({ length, composition })
  • T.unique.date, .whereby({ min, max }), .past, .past.whereby({ min }), .future, and .future.whereby({ max })

Each takes the same options as the ordinary builder of that kind. There is no T.unique.number.integer.sequence, because a sequence never repeats anyway.

Collections hold distinct members within each value they fabricate. Two separate values can share members.

  • T.unique.array(member).whereby({ length }): no two elements of the one array are the same.
  • T.unique.record(key, value).whereby({ size }): no two keys collide, so a record holds exactly the size drawn. That is why size here is a number or { min?, max, distribution? }, not T.record's { max, minTried }.

Running out

How a builder runs out depends on whether it knows how many values it has.

A finite set yields each value exactly once, in random order. This covers an enum, a uniform integer range, a bigint range, a uniform date range, and a string whose length and composition allow only so many strings. The draw after the last value throws FabricatorError.UniqueExhaustedError, whatever the salt.

Anything else is redrawn while it repeats a value already produced: a continuous number, a skewed range, an object in a unique array. After redraws repeats in a row, it gives up with FabricatorError.UniqueRedrawsError. The default scales with how many values have been produced, which is enough to fill a uniform domain down to its last value. A skewed distribution makes its rarest values hard to find, so pass a larger redraws in .whereby(...) if you need them. redraws: 0 means one draw and no retries.

A collection checks its member first. If the member has fewer distinct values than length.max or size.max, new Fabricator(...) throws FabricatorError.UniqueCapacityError. So T.unique.array(T.boolean).whereby({ length: { max: 3 } }) fails when you build it, not on whichever draw first happens to need a third boolean.

What counts as the same value

Plain data compares by content: primitives by value, a Date by its time, and arrays and plain objects by what they contain. Anything else, such as a symbol, a Map, or a class instance, compares by identity.

To compare array members by one part of them, call .by(key) before .whereby(...):

T.unique
  .array(
    T.object({
      email: T.enum.uniform(["ada@example.com", "bob@example.com"]),
      age: T.number.integer.whereby({ min: 18, max: 90 }),
    }),
  )
  .by((user) => user.email)
  .whereby({ length: 2 });

With .by, members are always redrawn while their key repeats. Different members can share a key, so there is no capacity check when you build it, and running out shows up as UniqueRedrawsError.

Overrides and .as()

A per-call override on a unique field is recorded, so no later draw repeats it. Overriding with a value that was already produced is allowed. A value outside the field's range uses up none of it.

There is no .as(produce) on the builders. Calling .as(produce) on a unique schema would replace the draw, and the promise of uniqueness with it.

Enumeration

combinatorial and coverage never pin a unique leaf; it keeps drawing in every instance. When a leaf has fewer values than the enumeration has instances, it uses every value once and then starts a new round instead of throwing. The same schema still throws when built anywhere else. A unique collection never repeats a member within one value, even in an enumeration.

To know up front whether every instance can get distinct values, compare capacity(schema) with the enumeration's size:

const { T, coverage, capacity } = initialize();
 
const Shirt = T.object({
  size: T.enum.uniform(["xs", "s", "m", "l", "xl"]),
  sku: T.unique.enum.uniform(["A1", "A2"]),
});
 
coverage(Shirt).size; // 5n
capacity(Shirt); // 2n — some instances will share a sku

capacity(schema)

capacity(schema) returns how many times one new Fabricator of schema can fabricate() before a unique leaf runs out, as a bigint. It returns undefined when no leaf has a known limit. The most limited leaf decides it:

const { T, capacity } = initialize();
 
const id = T.unique.number.integer.whereby({ min: 1, max: 100 });
 
capacity(T.object({ id })); // 100n
capacity(T.array(T.object({ id })).whereby({ length: { max: 10 } })); // 10n

A leaf inside an array or record is divided by that collection's length.max or size.max, since one fabrication can reach it that many times. A leaf that may not draw at all, such as one inside T.optional or one T.choice option, is counted as if it always draws.

It doesn't count a unique collection's members, which are only distinct within each value, or a field fixed with .override(), a T.recursive body, or anything under .as(...).

capacity reads the schema without building it, so it doesn't change any later draw. It counts for a new Fabricator, not for how much an existing one has already used.

Reproducibility

A unique field replays like any other: the same salt and clock give the same values in the same order.

TypeBox

A unique array converts to Type.Array(member, { uniqueItems: true }), and a unique record states its size as minProperties and maxProperties. Unique leaves convert like their kind. See TypeBox.