Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active September 30, 2024 19:20
Show Gist options
  • Select an option

  • Save Phryxia/a95ee9b73eb1dd0718b82932d2d04ffb to your computer and use it in GitHub Desktop.

Select an option

Save Phryxia/a95ee9b73eb1dd0718b82932d2d04ffb to your computer and use it in GitHub Desktop.
TypeScript implementation of simple adjacent iterator
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);
}
@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

Update

  • 2024-10-01: Replaced Generator to pure Iterator. This improved the performance about 2 ~ 4 times. When n increases, the performance of Generator drops more than 70%.

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