Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active July 13, 2023 16:43
Show Gist options
  • Save Phryxia/a95ee9b73eb1dd0718b82932d2d04ffb to your computer and use it in GitHub Desktop.
Save Phryxia/a95ee9b73eb1dd0718b82932d2d04ffb to your computer and use it in GitHub Desktop.
TypeScript implementation of simple adjacent iterator
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;
}
@Phryxia
Copy link
Author

Phryxia commented Jul 5, 2023

Very useful when you're dealing geometric things. Also this is error-free when there is not enough things in your array.

Example

console.log(...adjacentPairs([0, 1, 2], 2, false)) // [0, 1], [1, 2]
console.log(...adjacentPairs([0, 1, 2], 2, true)) // [0, 1], [1, 2], [2, 0]
console.log(...adjacentPairs([0, 1, 2], 3, false)) // [0, 1, 2]
console.log(...adjacentPairs([0, 1, 2], 3, true)) // [0, 1, 2], [1, 2, 0], [2, 0, 1]
console.log(...adjacentPairs([0], 2, true)) // nothing
console.log(...adjacentPairs([], 2, true)) // nothing

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