citedSources function

List<RagSource> citedSources(
  1. String text,
  2. List<RagSource> sources
)

The members of sources that text cites as [n] or [n, m], in order of first citation. Numbers without a matching source are ignored.

Implementation

List<RagSource> citedSources(String text, List<RagSource> sources) {
  final byNumber = {for (final s in sources) s.number: s};
  final seen = <int>{};
  final out = <RagSource>[];
  for (final m in _citation.allMatches(text)) {
    for (final part in m.group(1)!.split(',')) {
      // `tryParse`, because a model can write a digit run wider than 64 bits
      // and a citation is never worth throwing from a getter.
      final n = int.tryParse(part.trim());
      if (n == null) continue;
      final source = byNumber[n];
      if (source != null && seen.add(n)) out.add(source);
    }
  }
  return out;
}