Skip to content
This repository has been archived by the owner on Feb 1, 2024. It is now read-only.

Commit

Permalink
feat: Add stepBy
Browse files Browse the repository at this point in the history
  • Loading branch information
shun-shobon committed Dec 27, 2022
1 parent 1e98c8a commit 177c754
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions mod.ts
Expand Up @@ -14,6 +14,7 @@ export * from "./src/product.ts";
export * from "./src/range.ts";
export * from "./src/reduce.ts";
export * from "./src/skip.ts";
export * from "./src/stepBy.ts";
export * from "./src/sum.ts";
export * from "./src/take.ts";
export * from "./src/toArray.ts";
Expand Down
45 changes: 45 additions & 0 deletions src/stepBy.ts
@@ -0,0 +1,45 @@
export function stepBy<T>(n: number): (_: Iterator<T>) => Iterator<T> {
return (iter) => {
let isFirstTake = true;

return {
next() {
if (isFirstTake) {
isFirstTake = false;
return iter.next();
} else {
for (let i = 0; i < n - 1; i++) {
const result = iter.next();
if (result.done) return result;
}

return iter.next();
}
},
};
};
}

export function asyncStepBy<T>(
n: number,
): (_: AsyncIterator<T>) => AsyncIterator<T> {
return (iter) => {
let isFirstTake = true;

return {
async next() {
if (isFirstTake) {
isFirstTake = false;
return iter.next();
} else {
for (let i = 0; i < n - 1; i++) {
const result = await iter.next();
if (result.done) return result;
}

return iter.next();
}
},
};
};
}
24 changes: 24 additions & 0 deletions src/stepBy_test.ts
@@ -0,0 +1,24 @@
import { assertObjectMatch } from "../dev_deps.ts";
import { toAsync } from "./toAsync.ts";

import { asyncStepBy, stepBy } from "./stepBy.ts";

Deno.test("skip", () => {
const a = [0, 1, 2, 3, 4, 5];

const iter = stepBy(2)(a.values());
assertObjectMatch(iter.next(), { value: 0 });
assertObjectMatch(iter.next(), { value: 2 });
assertObjectMatch(iter.next(), { value: 4 });
assertObjectMatch(iter.next(), { done: true });
});

Deno.test("asyncSkip", async () => {
const a = [0, 1, 2, 3, 4, 5];

const iter = asyncStepBy(2)(toAsync(a.values()));
assertObjectMatch(await iter.next(), { value: 0 });
assertObjectMatch(await iter.next(), { value: 2 });
assertObjectMatch(await iter.next(), { value: 4 });
assertObjectMatch(await iter.next(), { done: true });
});

0 comments on commit 177c754

Please sign in to comment.