From cc4e4efce4b18d5fa525d1b7d46e4f5e33885467 Mon Sep 17 00:00:00 2001 From: ryoppippi <1560508+ryoppippi@users.noreply.github.com> Date: Sun, 25 Aug 2024 16:16:37 +0100 Subject: [PATCH] feat(reverse): introduce reverse --- reverse.ts | 24 ++++++++++++++++++++++++ reverse_test.ts | 18 ++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 reverse.ts create mode 100644 reverse_test.ts diff --git a/reverse.ts b/reverse.ts new file mode 100644 index 0000000..c697b5f --- /dev/null +++ b/reverse.ts @@ -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(iterable: Iterable): Iterable { + return { + *[Symbol.iterator]() { + const array = [...iterable]; + for (let i = array.length - 1; i >= 0; i--) { + yield array[i]; + } + }, + }; +} diff --git a/reverse_test.ts b/reverse_test.ts new file mode 100644 index 0000000..40388fe --- /dev/null +++ b/reverse_test.ts @@ -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>>(true); +}); + +await test("reverse with empty iterable", () => { + const result = reverse([] as number[]); + const expected = []; + assertEquals(result, expected); + assertType>(true); +});