willryan / factory.ts

A library to ease creation of factories for test data for Typescript
MIT License
425 stars 23 forks source link

Question: How to create a factory outputs tuples? #72

Open ranmocy opened 1 year ago

ranmocy commented 1 year ago

Currently the builder interface looks like this:

export declare type Builder<T, K extends keyof T = keyof T> = {
    [P in K]: T[P] | Generator<T[P]> | Derived<T, T[P]>;
};

Which seems like only could describe objects. Would it be possible to create a factory generates tuples? Tuple has fixed length ([number, number]), where array has arbitrary length (number[]).

What I'm trying to get is a Factory<[number, number]>. The best version I could get is:

const generator: Generator<[number, number]> = each<[number, number]>(() => [
  faker.datatype.number(),
  faker.datatype.number(),
])
const factory = makeFactory<[number, number]>(generator.build(0))

Which is not randomized, and calling factory.build() gives me an object:

{
  "0": 80479,
  "1": 32384,
  "length": 2
}

Any suggestion?

willryan commented 1 year ago

Hi, sorry for the slow response. I checked and tuples work as members of an object, so if nothing else you can create a pointless wrapper around the actual tuple, e.g.

const factory = Sync.makeFactory<{ foo: [number, number] }>(
  {
    _: Sync.each((seq) => [seq * 2, seq * 2 + 1]),
  },
  { startingSequenceNumber: 1 }
);
const tupleBuilder = () => factory.build()._;
const value = tupleBuilder();
expect(value.foo).toEqual([2, 3]);

I don't have a good solution (yet) for giving a different Generator to each element of the tuple, although there are reasonable ways around this by passing the seqNum down to each element. Also, this be aided by the work I'm trying to do to address #55.