parseMapEntry<K, V> static method

MapEntry<K, V>? parseMapEntry<K, V>(
  1. Object? value, {
  2. MapEntry<K, V>? def,
  3. TypeElementParser<K>? keyParser,
  4. TypeElementParser<V>? valueParser,
})

Tries to parse a MapEntry.

  • Returns def if value is null or an empty String.

Implementation

static MapEntry<K, V>? parseMapEntry<K, V>(Object? value,
    {MapEntry<K, V>? def,
    TypeElementParser<K>? keyParser,
    TypeElementParser<V>? valueParser}) {
  if (value == null) return def;

  if (value is MapEntry<K, V>) {
    return value;
  }

  keyParser ??= parserFor<K>();
  keyParser ??= (k) => k as K;

  valueParser ??= parserFor<V>();
  valueParser ??= (v) => v as V;

  if (value is MapEntry) {
    return MapEntry(keyParser(value.key) as K, valueParser(value.value) as V);
  } else if (value is Iterable) {
    var k = value.elementAt(0);
    var v = value.elementAt(1);
    return MapEntry(keyParser(k) as K, valueParser(v) as V);
  } else if (value is num && value is K && null is V) {
    return MapEntry<K, V>(value as K, null as V);
  } else {
    var s = '$value'.trim();
    if (s.isEmpty) return def;

    var idx = s.indexOf(_regexpKeyValueDelimiter);
    if (idx >= 0) {
      var k = s.substring(0, idx);
      var v = s.substring(idx + 1);
      return MapEntry(keyParser(k) as K, valueParser(v) as V);
    }
    return MapEntry(keyParser(s) as K, null as V);
  }
}