Skip to content

Commit e0324c2

Browse files
committed
chore: use custom isObjectEmpty that is O(1) instead of O(N). Important for large schemas
1 parent 6b81bd3 commit e0324c2

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

src/helpers/isObjectEmpty.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
type EmptyObject = { [x: string]: never } | null | undefined;
2+
3+
export function isObjectEmpty(value: object | null | undefined): value is EmptyObject {
4+
if (!value) {
5+
return true;
6+
}
7+
8+
for (const prop in value) {
9+
if (Object.prototype.hasOwnProperty.call(value, prop)) {
10+
return false;
11+
}
12+
}
13+
14+
return true;
15+
}

src/tools/mongodb/metadata/collectionSchema.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { getSimplifiedSchema } from "mongodb-schema";
66
import z from "zod";
77
import { ONE_MB } from "../../../helpers/constants.js";
88
import { collectCursorUntilMaxBytesLimit } from "../../../helpers/collectCursorUntilMaxBytes.js";
9+
import { isObjectEmpty } from "../../../helpers/isObjectEmpty.js";
910

1011
export class CollectionSchemaTool extends MongoDBToolBase {
1112
public name = "collection-schema";
@@ -32,8 +33,7 @@ export class CollectionSchemaTool extends MongoDBToolBase {
3233
});
3334
const schema = await getSimplifiedSchema(documents);
3435

35-
const fieldsCount = Object.entries(schema).length;
36-
if (fieldsCount === 0) {
36+
if (isObjectEmpty(schema)) {
3737
return {
3838
content: [
3939
{
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { isObjectEmpty } from "../../../src/helpers/isObjectEmpty.js";
2+
import { describe, expect, it } from "vitest";
3+
4+
describe("isObjectEmpty", () => {
5+
it("returns true for null", () => {
6+
expect(isObjectEmpty(null)).toBe(true);
7+
});
8+
9+
it("returns true for undefined", () => {
10+
expect(isObjectEmpty(undefined)).toBe(true);
11+
});
12+
13+
it("returns true for empty object", () => {
14+
expect(isObjectEmpty({})).toBe(true);
15+
});
16+
17+
it("returns false for object with properties", () => {
18+
expect(isObjectEmpty({ a: 1 })).toBe(false);
19+
});
20+
});

0 commit comments

Comments
 (0)