Skip to content

Commit

Permalink
Merge pull request #20 from Baek2back/python/zip-longest
Browse files Browse the repository at this point in the history
feat(zip-longest): naive implementation
  • Loading branch information
Baek2back authored Jul 31, 2024
2 parents 6bcc375 + 23e0cdd commit 0e8d4be
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/python/src/itertools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from "./filterfalse";
export * from "./islice";
export * from "./repeat";
export * from "./starmap";
export * from "./zipLongest";
28 changes: 28 additions & 0 deletions packages/python/src/itertools/zipLongest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { zipLongest } from "./zipLongest";

describe("zipLongest", () => {
it("zipLongest with empty iterable", () => {
const result = [...zipLongest([], [])];
expect(result).toEqual([]);
});
it("should zip until the longest value", () => {
const result = [...zipLongest("ABCD", "xy", { fillvalue: "-" })];
expect(result).toEqual([
["A", "x"],
["B", "y"],
["C", "-"],
["D", "-"],
]);
});

it("should zip fill with undefined", () => {
const result = [...zipLongest("", "ABCD")];
expect(result).toEqual([
[undefined, "A"],
[undefined, "B"],
[undefined, "C"],
[undefined, "D"],
]);
});
});
23 changes: 23 additions & 0 deletions packages/python/src/itertools/zipLongest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { iter } from "../built-in";

export function* zipLongest<T1, T2, D>(
xs: Iterable<T1>,
ys: Iterable<T2>,
options: { fillvalue?: D } = {},
): IterableIterator<[T1 | D, T2 | D]> {
const { fillvalue } = options;
const [ixs, iys] = [iter(xs), iter(ys)];

while (true) {
const [x, y] = [ixs.next(), iys.next()];

if (x.done && y.done) {
return;
}

yield [
!x.done ? x.value : (fillvalue as D),
!y.done ? y.value : (fillvalue as D),
];
}
}

0 comments on commit 0e8d4be

Please sign in to comment.