Last active
July 13, 2023 16:43
-
-
Save Phryxia/a95ee9b73eb1dd0718b82932d2d04ffb to your computer and use it in GitHub Desktop.
TypeScript implementation of simple adjacent 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
function* adjacentPairs<T>(itr: Iterable<T>, n: number, isClosed: boolean) { | |
const first = new Array(n - 1) as T[]; | |
const buffer = new Array(n) as T[]; | |
let count = 0; | |
for (const value of itr) { | |
pull(buffer, value); | |
if (++count >= n) { | |
yield [...buffer]; | |
} else if (count < n) { | |
first[count - 1] = value; | |
} | |
} | |
if (count >= n && isClosed) { | |
for (const value of first) { | |
pull(buffer, value); | |
yield [...buffer]; | |
} | |
} | |
} | |
function pull<T>(values: T[], newValue: T) { | |
for (let i = 0; i < values.length - 1; ++i) { | |
values[i] = values[i + 1]; | |
} | |
values[values.length - 1] = newValue; | |
} |
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