I'm trying to write a generic method so that I can test equality of two variables, for example:
function shallow_equals(x, y) {
let
same_type = typeof x === typeof y,
is_object = typeof x === 'object';
if (!same_type) return false;
if (same_type && !is_object) return x === y;
// treat it as an object
if (Object.keys(x).length !== Object.keys(y).length) return false;
for (key of Object.keys(x)) {
if (x[key] !== y[key]) {
return false;
}
}
return true;
}
// shallow comparison of two objects
Object.prototype.equals = function(other) {
console.log('self ==>', this);
console.log('other ==>', other);
console.log('shallow equal?', shallow_equals(this, other));
}
let z = 4;
let w = 4;
z.equals(w);
I'm curious why the above doesn't work, as the two types it gets are:
[Number: 4] --> object
4 --> number
Why does this occur and what would be the proper way to have a function like this?