Line data Source code
1 : // Copyright 2026 The Authors. See the AUTHORS file for details.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // https://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : extension IterableChecks on Iterable {
16 : /// Return true if all items in this are also in [other]
17 : ///
18 : /// This is different to `ListEquality` in the
19 : /// [`collection`](https://pub.dev/packages/collection) package
20 : /// as this function does not require the list elements to be in the
21 : /// same order.
22 1 : bool hasTheSameElements<T>(Iterable<T> other) {
23 2 : if (isEmpty && other.isEmpty) {
24 : return true;
25 : }
26 :
27 3 : if (length != other.length) {
28 : return false;
29 : }
30 :
31 2 : var checklist = List<bool>.filled(other.length, false, growable: false);
32 :
33 3 : for (int i = 0; i < length; i++) {
34 : var found = false;
35 3 : for (var j = 0; j < other.length; j++) {
36 1 : if (checklist[j]) continue;
37 :
38 3 : if (elementAt(i) == other.elementAt(j)) {
39 1 : checklist[j] = true;
40 : found = true;
41 : break;
42 : }
43 : }
44 : if (!found) {
45 : return false;
46 : }
47 : }
48 :
49 : return true;
50 : }
51 :
52 : /// Return true if this is a sublist of [other].
53 : ///
54 : /// Does not care if the lists are in the same order.
55 1 : bool isSubList<T>(Iterable<T> other) {
56 3 : if (length > other.length) {
57 : return false;
58 : }
59 :
60 2 : var checklist = List<bool>.filled(other.length, false, growable: false);
61 :
62 3 : for (var i = 0; i < length; i++) {
63 : var found = false;
64 3 : for (var j = 0; j < other.length; j++) {
65 1 : if (checklist[j]) continue;
66 :
67 3 : if (elementAt(i) == other.elementAt(j)) {
68 1 : checklist[j] = true;
69 : found = true;
70 : break;
71 : }
72 : }
73 : if (!found) return false;
74 : }
75 : return true;
76 : }
77 : }
|