leafo / tableshape

Test the shape or structure of a Lua table, inspired by React.PropTypes & LPeg
111 stars 9 forks source link

add 'mixed' type #3

Closed s-ol closed 7 years ago

s-ol commented 8 years ago

i am not sure how the interface and semantics should look for this, but what I found to be missing was a way to specify mixed-type tables.

For example I often use tables that are mostly arrays of a fixed 'shape' but have extra fields with meta keys:

changes =
  origin: "user",
  { "changeset 1" },
  { "changeset 2" },
  { "changeset 3" }

If I didn't miss something in the README, I don't think its possible to specify a shape like that accurately (only by setting the rest and then making it open).

My implementation takes the highest integer key and applies it's shape to all following keys.

I didn't add any tests because I'm pretty sure you want a more clear interface anyway.

s-ol commented 8 years ago

Another example to make the current implementation clear:

shape = t.mixed {
  a = 3,
  t.integer,
  t.string
}

shape{ a=3, 1, "asd" } -- matches
shape{ a=3, 1, 2 } -- fails
shape{ a=3, 1, "asd", "bsd", "csd" } -- matches

shape{ a=3, 1 } -- matches. not sure if it should?
leafo commented 7 years ago

You should be able to do something like this now:

types.all_of {
  types.array_of(types.string)
  types.shape({
    origin = "user"
  }, { open = true })
}

to match something that looks like this:

{
  "a",
  "b",
  "c",
  origin = "user"
}

In this example though, the shape test is open meaning it would let additional keys through.