From 8def294b6b6c8f706687d7260e4e16d5959c9ec9 Mon Sep 17 00:00:00 2001 From: forest93 Date: Sun, 14 Jul 2024 23:33:51 +0800 Subject: [PATCH] LINQ: any / all --- .../src/linq/__tests__/anyAll.test.ts | 22 +++++++++++ packages/jscorlib/src/linq/anyAll.ts | 38 +++++++++++++++++++ packages/jscorlib/src/linq/index.ts | 1 + 3 files changed, 61 insertions(+) create mode 100644 packages/jscorlib/src/linq/__tests__/anyAll.test.ts create mode 100644 packages/jscorlib/src/linq/anyAll.ts diff --git a/packages/jscorlib/src/linq/__tests__/anyAll.test.ts b/packages/jscorlib/src/linq/__tests__/anyAll.test.ts new file mode 100644 index 0000000..9d9196c --- /dev/null +++ b/packages/jscorlib/src/linq/__tests__/anyAll.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { asLinq, registerLinqModule } from "../linqWrapper"; +import * as AnyAll from "../anyAll"; + +registerLinqModule(AnyAll); + +describe("anyAll", () => { + it("any", () => { + expect(asLinq([]).any()).toBe(false); + expect(asLinq([1]).any()).toBe(true); + expect(asLinq([1]).any(x => x > 3)).toBe(false); + expect(asLinq([1, 3, 5]).any(x => x > 3)).toBe(true); + }); + + it("all", () => { + expect(asLinq([]).all(() => false)).toBe(true); + expect(asLinq([1]).all(x => x > 0)).toBe(true); + expect(asLinq([1]).all(x => x > 3)).toBe(false); + expect(asLinq([1, 3, 5]).all(x => x > 0)).toBe(true); + expect(asLinq([1, 3, 5]).all(x => x > 3)).toBe(false); + }); +}); diff --git a/packages/jscorlib/src/linq/anyAll.ts b/packages/jscorlib/src/linq/anyAll.ts new file mode 100644 index 0000000..7dc3ac4 --- /dev/null +++ b/packages/jscorlib/src/linq/anyAll.ts @@ -0,0 +1,38 @@ +import type { LinqWrapper } from "./linqWrapper"; +import { SequenceElementPredicate } from "./typing"; + +export type AggregateAccumulator = (accumulate: TAccumulate, element: T) => TAccumulate; + +declare module "./linqWrapper" { + export interface LinqWrapper { + any(predicate?: SequenceElementPredicate): boolean; + all(predicate: SequenceElementPredicate): boolean; + } +} + +export function Linq$any( + this: LinqWrapper, + predicate?: SequenceElementPredicate, +): boolean { + if (predicate) { + for (const e of this.unwrap()) { + if (predicate(e)) return true; + } + return false; + } + + for (const e of this.unwrap()) { + return true; + } + return false; +} + +export function Linq$all( + this: LinqWrapper, + predicate: SequenceElementPredicate, +): boolean { + for (const e of this.unwrap()) { + if (!predicate(e)) return false; + } + return true; +} diff --git a/packages/jscorlib/src/linq/index.ts b/packages/jscorlib/src/linq/index.ts index 27843bb..ee92242 100644 --- a/packages/jscorlib/src/linq/index.ts +++ b/packages/jscorlib/src/linq/index.ts @@ -7,6 +7,7 @@ * @module */ export * as Aggregate from "./aggregate"; +export * as AnyAll from "./anyAll"; export * as Chunk from "./chunk"; export * as Collect from "./collect"; export * as CollectHashMap from "./collectHashMap";