Skip to content

Commit f00f457

Browse files
committed
refactor(json-crdt-extensions): 💡 generalize character iteration
1 parent 3ed7057 commit f00f457

File tree

1 file changed

+28
-16
lines changed
  • src/json-crdt-extensions/peritext/editor

1 file changed

+28
-16
lines changed

src/json-crdt-extensions/peritext/editor/Editor.ts

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -104,35 +104,47 @@ export class Editor<T = string> {
104104
}
105105

106106
/**
107-
* Returns a forward iterator through visible text, one character at a time,
108-
* starting from a given ID.
107+
* Returns an iterator through visible text, one `step` characters at a time,
108+
* starting from a given {@link Point}.
109109
*
110-
* @param id ID to start from.
111-
* @param chunk Chunk to start from.
110+
* @param start The starting point.
111+
* @param step Number of visible characters to skip.
112112
* @returns The next visible character iterator.
113113
*/
114-
public fwd(start: Point<T>): CharIterator<T> {
114+
public walk(start: Point<T>, step: number = 1): CharIterator<T> {
115115
let point: Point<T> | undefined = start.clone();
116116
return () => {
117117
if (!point) return;
118-
const char = point.rightChar();
118+
const char = step > 0 ? point.rightChar() : point.leftChar();
119119
if (!char) return point = undefined;
120-
const end = point.move(1);
120+
const end = point.move(step);
121121
if (end) point = undefined;
122122
return char;
123123
};
124124
}
125125

126+
/**
127+
* Returns a forward iterator through visible text, one character at a time,
128+
* starting from a given {@link Point}.
129+
*
130+
* @param start The starting point.
131+
* @param chunk Chunk to start from.
132+
* @returns The next visible character iterator.
133+
*/
134+
public fwd(start: Point<T>): CharIterator<T> {
135+
return this.walk(start, 1);
136+
}
137+
138+
/**
139+
* Returns a backward iterator through visible text, one character at a time,
140+
* starting from a given {@link Point}.
141+
*
142+
* @param start The starting point.
143+
* @param chunk Chunk to start from.
144+
* @returns The previous visible character iterator.
145+
*/
126146
public bwd(start: Point<T>): CharIterator<T> {
127-
let point: Point<T> | undefined = start.clone();
128-
return () => {
129-
if (!point) return;
130-
const char = point.leftChar();
131-
if (!char) return point = undefined;
132-
const end = point.move(-1);
133-
if (end) point = undefined;
134-
return char;
135-
};
147+
return this.walk(start, -1);
136148
}
137149

138150
/**

0 commit comments

Comments
 (0)