bool matchesQuery()

in web/samples_index/lib/src/search.dart [5:56]


bool matchesQuery(String query, String sampleAttributes) {
  if (query.isEmpty) {
    return true;
  }
  var queryWords = query.split(' ')..removeWhere((s) => s.isEmpty);
  var attributes = sampleAttributes.split(' ')..removeWhere((s) => s.isEmpty);

  // Test for type filter
  // This will check whether a type parameter is present in the
  // search query, and return false if the self type mismatches
  // the query type
  for (var word in queryWords) {
    if ((word.contains('type:') && !attributes.contains(word)) ||
        (word.contains('platform:') && !attributes.contains('type:demo'))) {
      return false;
    }
  }

  // Test for exact matches
  if (attributes.contains(query)) {
    return true;
  }

  // Test for exact matches for keywords
  var matches = 0;
  for (var word in queryWords) {
    if (attributes.contains(word)) {
      matches++;
    }
    if (matches == queryWords.length) {
      return true;
    }
  }

  // Test for queries whose keywords are a substring of any attribute
  // e.g. searching "kitten tag:cats" is a match for a sample with the
  // attributes "kittens tag:cats"
  matches = 0;
  for (var attribute in attributes) {
    for (var queryWord in queryWords) {
      if (attribute.startsWith(queryWord)) {
        matches++;
      }
    }
    // Only return true if each search term was matched
    if (matches == queryWords.length) {
      return true;
    }
  }

  return false;
}