Skip to content

Commit

Permalink
LINQ: any / all
Browse files Browse the repository at this point in the history
  • Loading branch information
CXuesong committed Jul 14, 2024
1 parent 2339929 commit 8def294
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/jscorlib/src/linq/__tests__/anyAll.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
38 changes: 38 additions & 0 deletions packages/jscorlib/src/linq/anyAll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { LinqWrapper } from "./linqWrapper";
import { SequenceElementPredicate } from "./typing";

export type AggregateAccumulator<T, TAccumulate> = (accumulate: TAccumulate, element: T) => TAccumulate;

declare module "./linqWrapper" {
export interface LinqWrapper<T> {
any(predicate?: SequenceElementPredicate<T>): boolean;
all(predicate: SequenceElementPredicate<T>): boolean;
}
}

export function Linq$any<T>(
this: LinqWrapper<T>,
predicate?: SequenceElementPredicate<T>,
): 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<T>(
this: LinqWrapper<T>,
predicate: SequenceElementPredicate<T>,
): boolean {
for (const e of this.unwrap()) {
if (!predicate(e)) return false;
}
return true;
}
1 change: 1 addition & 0 deletions packages/jscorlib/src/linq/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down

0 comments on commit 8def294

Please sign in to comment.