Last active
September 30, 2024 19:20
-
-
Save Phryxia/a95ee9b73eb1dd0718b82932d2d04ffb to your computer and use it in GitHub Desktop.
TypeScript implementation of simple adjacent iterator
This file contains hidden or 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 function adjacentPairs<T>( | |
| itr: Iterable<T>, | |
| n: number, | |
| isClosed?: boolean, | |
| ): IterableIterator<T[]> { | |
| const buffer = new Array<T>(n); | |
| const it = itr[Symbol.iterator](); | |
| let res = it.next(); | |
| for (let i = 0; i < n; ++i) { | |
| if (res.done) { | |
| return { | |
| [Symbol.iterator]() { | |
| return this; | |
| }, | |
| next() { | |
| return { | |
| value: undefined, | |
| done: true, | |
| }; | |
| }, | |
| }; | |
| } | |
| buffer[i] = res.value; | |
| res = it.next(); | |
| } | |
| const first = buffer.slice(0, n - 1); | |
| let isEnd = false; | |
| let ringCount = 0; | |
| return { | |
| [Symbol.iterator]() { | |
| return this; | |
| }, | |
| next() { | |
| if (isEnd) { | |
| return { | |
| value: undefined, | |
| done: true, | |
| }; | |
| } | |
| const ret = buffer.slice(); | |
| if (res.done) { | |
| if (isClosed) { | |
| if (ringCount < n - 1) { | |
| pull(buffer, first[ringCount++]); | |
| } else { | |
| isEnd = true; | |
| } | |
| } else { | |
| isEnd = true; | |
| } | |
| } else { | |
| pull(buffer, res.value); | |
| res = it.next(); | |
| } | |
| return { | |
| value: ret, | |
| done: false, | |
| }; | |
| }, | |
| }; | |
| } | |
| function pull<T>(values: T[], newValue: T) { | |
| values.shift(); | |
| values.push(newValue); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful when you're dealing geometric things. Also this is error-free when there is not enough things in your array.
Example
Update
Generatorto pureIterator. This improved the performance about 2 ~ 4 times. Whennincreases, the performance of Generator drops more than 70%.