
Sponsored
Sponsored
In this approach, we make use of direct language features to determine if an object is an instance of a given class. Most programming languages have built-in operators or functions to check instanceof relationships, such as 'instanceof' in JavaScript, or 'isinstance' in Python.
Time Complexity: O(n), where n is the depth of prototype chain.
Space Complexity: O(1), no extra space is used.
1// C does not have built-in object-oriented features like instanceof. Instead, this would be handled through custom implementations or a different language.C does not inherently support OOP features necessary for this check since it's not an object-oriented language. Generally, such operations would be abstracted using structures and function pointers, if needed.
This approach is specifically for JavaScript where we manually traverse the prototype chain of the object to check if the class prototype is found in the chain.
Time Complexity: O(n), where n is the depth of the prototype chain.
Space Complexity: O(1)
1function checkIfInstanceOf(obj, cls) {
2 if (obj === null || obj === undefined) return false;
3 let prototype = Object.getPrototypeOf(obj);
4 while (prototype) {
5 if (prototype === cls.prototype) {
6 return true;
7 }
8 prototype = Object.getPrototypeOf(prototype);
9 }
10 return false;
11}This solution manually walks up the prototype chain by using 'Object.getPrototypeOf'. For each step in the chain, it verifies if the current prototype matches the prototype of the class, which ensures that subclass checks are also performed. This method provides finer control and understanding of the checking process.