censorMap static method

Map<String, dynamic> censorMap(
  1. Map<String, dynamic> map,
  2. String censorString,
  3. List<CensorElement> elementsToCensor
)

Censors the given elementsToCensor in the given map with the given censorString.

Implementation

static Map<String, dynamic> censorMap(Map<String, dynamic> map,
    String censorString, List<CensorElement> elementsToCensor) {
  if (elementsToCensor.isEmpty) {
    // short circuit if there are no censors to apply
    return map;
  }

  Map<String, dynamic> censoredMap = <String, dynamic>{};

  map.forEach((key, value) {
    if (elementShouldBeCensored(key, elementsToCensor)) {
      if (value == null) {
        censoredMap[key] =
            null; // don't need to worry about censoring something that's null (don't replace null with the censor string)
      } else if (isJsonMap(value)) {
        // replace with empty dictionary
        censoredMap[key] = <String, dynamic>{};
      } else if (isJsonList(value)) {
        // replace with empty list
        censoredMap[key] = <dynamic>[];
      } else {
        // replace with censor string
        censoredMap[key] = censorString;
      }
    } else {
      if (value == null) {
        censoredMap[key] =
            null; // don't need to worry about censoring something that's null (don't replace null with the censor string)
      } else if (isJsonMap(value)) {
        // recursively censor inner dictionaries
        censoredMap[key] = censorMap(value, censorString, elementsToCensor);
      } else if (isJsonList(value)) {
        // recursively censor list elements
        censoredMap[key] = censorList(value, censorString, elementsToCensor);
      } else {
        // keep value as is
        censoredMap[key] = value;
      }
    }
  });

  return censoredMap;
}