Skip to content

Commit 2f8df73

Browse files
committed
Impl iterator pattern: word iterator.
1 parent 435e111 commit 2f8df73

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import 'text/text.dart';
2+
3+
void main() {
4+
final text = Text(
5+
'Iterator is a behavioral design pattern that lets you traverse elements '
6+
'of a collection without exposing its underlying representation '
7+
'(list, stack, tree, etc.).',
8+
);
9+
10+
for (final s in text) {
11+
print(s);
12+
}
13+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import '../text/text.dart';
2+
3+
class WordIterator extends Iterator<String> {
4+
WordIterator(this._text);
5+
6+
@override
7+
String get current => _currWord!;
8+
9+
@override
10+
bool moveNext() {
11+
final start = _lastIndex;
12+
13+
while (_searchNextSpaceChar(' ')) {
14+
// ++
15+
}
16+
17+
_currWord = _getWord(start, _lastIndex);
18+
return _currWord!.isNotEmpty;
19+
}
20+
21+
final Text _text;
22+
int _lastIndex = 0;
23+
String? _currWord;
24+
25+
bool _searchNextSpaceChar(String char) {
26+
final isTextEnd = _lastIndex >= _text.text.length;
27+
28+
if (isTextEnd) {
29+
return false;
30+
}
31+
32+
final isNotSpaceChar = _text.text[_lastIndex++] != char;
33+
return isNotSpaceChar;
34+
}
35+
36+
String _getWord(int start, int end) {
37+
final noWordChars = RegExp(r'\W');
38+
return _text.text
39+
.substring(
40+
start,
41+
_lastIndex,
42+
)
43+
.replaceAll(
44+
noWordChars,
45+
'',
46+
);
47+
}
48+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import '../pattern/word_iterator.dart';
2+
3+
class Text extends Iterable<String> {
4+
final String text;
5+
6+
Text(this.text);
7+
8+
@override
9+
Iterator<String> get iterator => WordIterator(this);
10+
}

0 commit comments

Comments
 (0)