suggestion: validate inputs being of type object, early bail-out if necessary#38
suggestion: validate inputs being of type object, early bail-out if necessary#38ziir wants to merge 2 commits intomoroshko:masterfrom
Conversation
… with failing tests
01e4cec to
6d6b67f
Compare
|
I think this library should focus solely on performing shallow equality checks for arrays and objects, and it should disallow other types as inputs. Based on this, I think it would be beneficial to add a validation like this: function shallowEqual<T extends Comparable>(a: T, b: T): boolean {
const aIsArr = Array.isArray(a);
const bIsArr = Array.isArray(b);
if (aIsArr !== bIsArr) {
return false;
}
if (aIsArr && bIsArr) {
return shallowEqualArrays(a, b);
}
// NEW
if (Object.prototype.toString.call(a) !== "[object Object]" ||
Object.prototype.toString.call(b) !== "[object Object]") {
throw new Error("arguments must be both arrays or both objects")
}
return shallowEqualObjects(a, b);
}With this change, calling Additionally, I believe If a user prefers type checking to ensure safety and is okay with the runtime penalty, they can use |
Hi!
Thank you for maintaining this project.
We've been using it in production for the past 6months as our go-to shallow-equality-check utility.
However, we've recently been bit by a bug caused by our failure to ensure the input parameters we're passing to
shallowEqualsare indeed objects or arrays.To illustrate, we've had a specific case where the input values were different numbers, unfortunately marked as
any:I know this library is meant to be used with input values which the consumer knows are objects, and the library does not aim to provide a shallow-equality-check utility accounting for all the possible types & matching edge-cases.
However, I do believe it would be a valuable addition to introduce a bare minimum
typeof-based validation at the right place, to avoid consumers treating some non-object-typeof values as being "shallow-equal", which is what this PR does.I believe this direction still matches the project's philosophy since there are a couple of existing, similar-to-some-degree checks in the current implementation, such as loosely checking for falsy values in
shallowEqualArraysnotably.Thank you for your consideration.