Last active
August 24, 2022 11:18
-
-
Save Phryxia/e25909a0f8c7117f1a4290f0126d9e34 to your computer and use it in GitHub Desktop.
TypeScript implementation for cloneable string iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 changeindex
into some closure like things.