在 Ruby 中,redo
可以使用关键字返回到循环的开头而不消耗输入。我想对for...of
JavaScript 中的循环做同样的事情。
const scan = lexer => function* (string) {
let [token, table] = lexer;
for (const character of string) {
const next = table.get(character);
if (next) {
[token, table] = next.value;
} else if (token) {
yield token.value;
[token, table] = lexer;
// redo the current iteration without consuming input
} else {
throw new SyntaxError("Unexpected character", character);
}
}
if (token) yield token.value;
else throw new SyntaxError("Unexpected end of input");
}
通常,您只需不增加常规for
循环的索引即可。但是,我必须使用for...of
循环,因为它循环遍历字符串的 Unicode 代码点,而常规for
循环将遍历字符串的 UTF-16 代码单元。
如何在不重复代码的情况下回到循环的开头?