Skip to content

Commit

Permalink
feat(reverse): introduce reverse
Browse files Browse the repository at this point in the history
  • Loading branch information
ryoppippi committed Aug 25, 2024
1 parent 2cf67f5 commit cc4e4ef
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
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);
});

0 comments on commit cc4e4ef

Please sign in to comment.