From a84450fc231dfd6859ee39d2f41c02c97f370596 Mon Sep 17 00:00:00 2001 From: JOLIMAITRE Matthieu Date: Sat, 15 Jun 2024 01:28:46 +0200 Subject: [PATCH] add range class --- src/lib.ts | 3 ++- src/lib/Range.ts | 27 +++++++++++++++++++++++++++ src/lib/utils.ts | 4 ---- 3 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 src/lib/Range.ts diff --git a/src/lib.ts b/src/lib.ts index 8d587e0..16a6083 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -3,8 +3,9 @@ export type { Arr, ClassOf, Constructible, Function, InstanceOf, KeyOfType, Tail // functions export { all, enumerate, filter, filter_map, it, Iter, map, zip } from "./lib/iter.ts"; -export { log_from, next, range, split_promise, wait } from "./lib/utils.ts"; +export { log_from, next, split_promise, wait } from "./lib/utils.ts"; // Structures export { Chain } from "./lib/Chain.ts"; export { Channel } from "./lib/Channel.ts"; +export { Range, range } from "./lib/Range.ts"; diff --git a/src/lib/Range.ts b/src/lib/Range.ts new file mode 100644 index 0000000..ddbe806 --- /dev/null +++ b/src/lib/Range.ts @@ -0,0 +1,27 @@ +export class Range { + from; + to; + + constructor(from: number, to: number) { + this.from = from; + this.to = to; + } + + *[Symbol.iterator](): Generator { + let index = this.from; + while (index < this.to) yield index++; + } + + includes(n: number) { + return (n > this.from) && (n < this.to); + } +} + +export function range(from: number, to: number) { + return new Range(from, to); +} + +Deno.test("range", async () => { + const { assertEquals } = await import("https://deno.land/std@0.224.0/assert/assert_equals.ts"); + assertEquals([...range(0, 4)], [0, 1, 2, 3]); +}); diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 0119f50..38eadea 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -18,10 +18,6 @@ export function next(iterator: Iterator) { else return result as T; } -export function* range(from: number, to: number) { - while (from < to) yield from++; -} - /** * usage: * ```ts