Skip to content

Commit

Permalink
Merge pull request #93 from Milly/no-prototype
Browse files Browse the repository at this point in the history
fix[isObjectOf]: no discover prototype properties
  • Loading branch information
lambdalisue authored Aug 8, 2024
2 parents 7d8bcbd + 0ec8074 commit f1c49f5
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
5 changes: 1 addition & 4 deletions is/object_of.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ export function isObjectOf<
Array.isArray(x)
) return false;
// Check each values
for (const k in predObj) {
if (!predObj[k]((x as T)[k])) return false;
}
return true;
return Object.keys(predObj).every((k) => predObj[k]((x as T)[k]));
},
"isObjectOf",
predObj,
Expand Down
56 changes: 55 additions & 1 deletion is/object_of_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ Deno.test("isObjectOf<T>", async (t) => {
assertEquals(
isObjectOf(predObj)({ a: 0, b: "a", c: true, d: "ignored" }),
true,
"Undefined properties are ignored",
);
assertEquals(
isObjectOf(predObj)(
Object.assign(() => void 0, { a: 0, b: "a", c: true }),
),
true,
"Function are treated as an object",
);
});

Expand Down Expand Up @@ -64,7 +66,7 @@ Deno.test("isObjectOf<T>", async (t) => {
const predObj = {
getFullYear: is.Function,
};
assertEquals(isObjectOf(predObj)(date), true, "Value is not an object");
assertEquals(isObjectOf(predObj)(date), true);
});

await t.step("predicated type is correct", () => {
Expand Down Expand Up @@ -98,4 +100,56 @@ Deno.test("isObjectOf<T>", async (t) => {
>(true);
}
});

await t.step(
"does not affect prototype properties of 'predObj'",
async (t) => {
const prototypeObj = {
a: is.Number,
b: is.Boolean,
};
// deno-lint-ignore ban-types
const predObj = Object.assign(Object.create(prototypeObj) as {}, {
c: is.String,
});

await t.step("returns true on T object", () => {
assertEquals(isObjectOf(predObj)({ c: "a" }), true);
assertEquals(
isObjectOf(predObj)({ a: "ignored", b: "ignored", c: "a" }),
true,
"Predicates defined in the prototype are ignored",
);
assertEquals(
isObjectOf(predObj)({ c: "a", d: "ignored" }),
true,
"Undefined properties are ignored",
);
assertEquals(
isObjectOf(predObj)(Object.assign(() => void 0, { c: "a" })),
true,
"Function are treated as an object",
);
});

await t.step("returns false on non T object", () => {
assertEquals(isObjectOf(predObj)("a"), false, "Value is not an object");
assertEquals(
isObjectOf(predObj)({ a: 0, b: true, c: 1 }),
false,
"Object have a different type property",
);
assertEquals(
isObjectOf(predObj)({ a: 0, b: true }),
false,
"Object does not have one property",
);
assertEquals(
isObjectOf({ 0: is.String })(["a"]),
false,
"Value is not an object",
);
});
},
);
});

0 comments on commit f1c49f5

Please sign in to comment.