Skip to content

Instantly share code, notes, and snippets.

@xavierchia
Created June 16, 2020 04:57
Show Gist options
  • Save xavierchia/94b3b478c879282793b80cb607046d52 to your computer and use it in GitHub Desktop.
Save xavierchia/94b3b478c879282793b80cb607046d52 to your computer and use it in GitHub Desktop.
<script src="simpletest.js"></script>
<script>
/*
The function isPrototypeOf should work just like Object.prototype.isPrototypeOf
Syntax:
Formula: isPrototypeOf(parentObject, childObject)
Arguments:
parentObject
childObject
Return Value: A Boolean indicating whether the calling object lies in the prototype chain of the specified object
Tests:
It should throw a typeError if childObject or parentObject are not objects [DONE]
It should return true if childObject is a prototype of parentObject [DONE]
It should return false if childObject is not a prototype of parentObject [DONE]
It should work for any number of prototype links
*/
function isPrototypeOf(parentObject, childObject) {
// Return false if you have reached the top of the prototype chain
if (childObject === null) {
return false;
}
// Check if parent and child objects are of type object
if (typeof parentObject !== 'object' || typeof childObject !== 'object') {
throw new TypeError('Parent or child is not object type');
}
// Return true if childObject is prototype of parentObject
if (Object.getPrototypeOf(childObject) === parentObject) {
return true;
}
// Recurse up the prototype chain to check ifPrototypeOf
else {
return isPrototypeOf(parentObject, Object.getPrototypeOf(childObject));
}
}
tests({
'It should throw a typeError if childObject or parentObject are not objects': function () {
var isTypeError = false;
try {
isPrototypeOf();
}
catch (e) {
isTypeError = e instanceof TypeError;
}
eq(isTypeError, true);
},
'It should return true if childObject is a prototype of parentObject': function() {
var parentObject = {name: 'xavier'};
var childObject = Object.create(parentObject);
eq(isPrototypeOf(parentObject, childObject), true);
},
'It should return false if childObject is not a prototype of parentObject': function() {
var parentObject = {name: 'xavier'};
var childObject = {name: 'ally'};
eq(isPrototypeOf(parentObject, childObject), false);
},
'It should work for any number of prototype links': function() {
var canine = {
bark: function() {
console.log('bark');
}
};
var dog = Object.create(canine);
dog.fetch = function() {
console.log('fetch');
};
var myDog = Object.create(dog);
eq(isPrototypeOf(canine, myDog), true);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment