dart-lang / code_builder

A fluent API for generating valid Dart source code
https://pub.dev/packages/code_builder
BSD 3-Clause "New" or "Revised" License
423 stars 66 forks source link

`LiteralMapExpression` needs support for collection-if expression #447

Open lukehutch opened 6 months ago

lukehutch commented 6 months ago

LiteralMapExpression does not yet support collection-if. This means it's not possible to generate the following:

{
  if (x != null) 'x' : x,
  if (y != null) 'y': y,
  if (z != null) 'z': z,
}

I need to be able to add these conditions in order to minimize the text-rendered size of sparse JSON maps.

Presumably the way to support this would be similar to how literalSpread works:

literalMap({
  collectionIf(refer('x').isNotNull(), 'x'): refer('x'),
  // ...
})

Expression.visitLiteralMapExpression will also need to be updated to support this (and it should work for sets and lists too)..