Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(reverse): introduce reverse #22

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions reverse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Returns the elements of an iterable in reverse order.
*
* @param iterable The iterable to reverse.
* @returns The elements of the iterable in reverse order.
*
* @example
* ```ts
* import { reverse } from "@core/iterutil/reverse";
*
* console.log([...reverse([1, 2, 3)]); // [3, 2, 1]
* console.log([...reverse([])]); // []
* ```
*/
export function reverse<T>(iterable: Iterable<T>): Iterable<T> {
return {
*[Symbol.iterator]() {
const array = [...iterable];
for (let i = array.length - 1; i >= 0; i--) {
yield array[i];
}
},
};
}
18 changes: 18 additions & 0 deletions reverse_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { test } from "@cross/test";
import { assertEquals } from "@std/assert";
import { assertType, type IsExact } from "@std/testing/types";
import { reverse } from "./reverse.ts";

await test("reverse with non empty iterable", () => {
const result = reverse([1, 2, 3, 4, 5] as const);
const expected = [5, 4, 3, 2, 1] as const;
assertEquals(result, expected);
assertType<IsExact<typeof result, Iterable<[5, 4, 3, 2, 1]>>>(true);
});

await test("reverse with empty iterable", () => {
const result = reverse([] as number[]);
const expected = [];
assertEquals(result, expected);
assertType<IsExact<typeof result, number[]>>(true);
});
Loading