List removeOverLappingMatches()

in lib/src/license_detection/license_detector.dart [172:226]


List<LicenseMatch> removeOverLappingMatches(List<LicenseMatch> matches) {
  var retain = List.filled(matches.length, false);
  var retainedmatches = <LicenseMatch>[];

  // We consider token density to retain matches of larger licenses
  // having lesser confidence when compared to a smaller license
  // haing a  perfect match.
  for (var i = 0; i < matches.length; i++) {
    var keep = true;
    final matchA = matches[i];
    final rangeA = Range(matchA.tokenRange.start, matchA.tokenRange.end);

    var proposals = <int, bool>{};
    for (var j = 0; j < matches.length; j++) {
      if (j == i) {
        break;
      }
      final matchB = matches[j];
      final rangeB = Range(matchB.tokenRange.start, matchB.tokenRange.end);
      // Check if matchA is larger license containing an insatnce of
      // smaller license within it and decide to whether retain it
      // or not by comapring their token densities. Example NPL
      // contains MPL.
      if (rangeA.contains(rangeB) && retain[j]) {
        final aConf = matchA.tokensClaimed * matchA.confidence;
        final bConf = matchB.tokensClaimed * matchB.confidence;

        // Retain both the licenses incase of a exact match,
        // so that it can be resolved by the user.
        if (aConf > bConf) {
          proposals[j] = true;
        } else if (bConf > aConf) {
          keep = false;
        }
      } else if (rangeA.overlapsWith(rangeB)) {
        keep = false;
      }
    }

    if (keep) {
      retain[i] = true;
      proposals.forEach((key, value) {
        retain[key] = value;
      });
    }
  }

  for (var i = 0; i < matches.length; i++) {
    if (retain[i]) {
      retainedmatches.add(matches[i]);
    }
  }

  return retainedmatches;
}