Skip to content

Commit

Permalink
Itertools/pairwise (#40)
Browse files Browse the repository at this point in the history
* feat(pairwise): implement operation

* chore: apply changeset
  • Loading branch information
Baek2back authored Aug 6, 2024
1 parent 42202d0 commit a54e4d1
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/tough-bananas-end.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@iter-x/python": patch
---

implement pairwise operation
26 changes: 26 additions & 0 deletions packages/python/src/itertools/pairwise.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { pairwise } from "./pairwise";

describe("pairwise", () => {
it("should generate pairwise iterator", () => {
const result = [...pairwise("ABCDEFG")];
expect(result).toEqual([
["A", "B"],
["B", "C"],
["C", "D"],
["D", "E"],
["E", "F"],
["F", "G"],
]);
});

it("should not generate any values when iterator is empty", () => {
const result = [...pairwise("")];
expect(result).toEqual([]);
});

it("should not generate any values when iterator is short to be pair", () => {
const result = [...pairwise("A")];
expect(result).toEqual([]);
});
});
19 changes: 19 additions & 0 deletions packages/python/src/itertools/pairwise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { iter } from "../built-in";

/**
* @example pairwise('ABCDEFG') -> AB BC CD DE EF FG
*/
export function* pairwise<T>(iterable: Iterable<T>): IterableIterator<[T, T]> {
const it = iter(iterable);
let item = it.next();
let prevValue = item.value;

if (item.done) return;

while (true) {
item = it.next();
if (item.done) return;
yield [prevValue, item.value];
prevValue = item.value;
}
}

0 comments on commit a54e4d1

Please # to comment.