dart-lang / core

This repository is home to core Dart packages.
https://pub.dev/publishers/dart.dev
BSD 3-Clause "New" or "Revised" License
12 stars 2 forks source link

Support short-hand for creating codecs/converters #255

Open matanlurey opened 7 years ago

matanlurey commented 7 years ago

Lots of Dart and Flutter users don't even know about package:convert or dart:convert, or when they do it seems difficult to get started - most code samples I've seen folks write static functions in the form of T convert<S, T>(S input) and ignore these packages.

Could we consider adding some simple short-hand classes/functions to make use easier?

class MapConverter<S, T> implements Converter<S, T> {
  const MapCodec(Map<S, T> map) => ...
}

final hexToName = const MapConverter(const {
  0x00: 'Zero',
  0x01: 'One',
  0x02: 'Two',
});

main() {
  print(hexToName.convert(0x01)); // Outputs 'One'.
}
main() {
  var /*Converter<int, String>*/ hexToName = asConverter((int value) {
    switch (value) {
      case 0x00: return 'Zero';
      ...
    }
  });
}
main() {
  var /*Codec<int, String>*/ hexCodec = asCodec(hexToName, nameToHex);
}
nex3 commented 7 years ago

I'd love to see asConverter() and asCodec() as constructors on the Converter and Codec classes. Constructors are the easiest thing to add to core libraries, too, since they don't have any backwards-incompatibility edge cases.

I'm down with MapConverter if you think that use-case is widespread enough to be worth a class.