Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active August 24, 2022 11:18
Show Gist options
  • Save Phryxia/e25909a0f8c7117f1a4290f0126d9e34 to your computer and use it in GitHub Desktop.
Save Phryxia/e25909a0f8c7117f1a4290f0126d9e34 to your computer and use it in GitHub Desktop.
TypeScript implementation for cloneable string iterator
export interface StringIterator extends IterableIterator<string> {
clone(): StringIterator
}
export function createStringIterator(s: string, index: number = 0): StringIterator {
return {
next(): IteratorResult<string> {
if (index >= s.length) {
return {
done: true,
value: undefined,
}
}
return {
done: false,
value: s[index++],
}
},
[Symbol.iterator]() {
return this
},
clone() {
return createStringIterator(s, index)
}
}
}
@Phryxia
Copy link
Author

Phryxia commented Aug 24, 2022

Useful when you implement parser-like-things, and you might have to branch with multiple possibilities. Built-in iterator doesn't support proper clone. You can generalize this to other types whenever the original target s is immutable. Just change index into some closure like things.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment