-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcheck-if-object-instance-of-class.js
45 lines (43 loc) · 1.16 KB
/
check-if-object-instance-of-class.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 2618. Check if Object Instance of Class
// 🟠 Medium
//
// https://leetcode.com/problems/check-if-object-instance-of-class/
//
// Tags: Javascript
// Get the provided object prototype and check if that matches the given class,
// keep going up the prototype chain until we find one that it matches or
// the chain ends.
//
// Time complexity: O(n) - It can go up the entire prototype chain or until it
// finds a class that matches.
// Space complexity: O(1) - The iterative version uses constant extra memory,
// we could use a recursive version with similar logic, but it would require
// extra memory.
//
// Runtime 115 ms Beats 27.90%
// Memory 51.1 MB Beats 95.40%
/**
* @param {any} obj
* @param {any} classFunction
* @return {boolean}
*/
var checkIfInstanceOf = function (obj, classFunction) {
if (
obj === null ||
obj === undefined ||
typeof classFunction !== "function"
) {
return false;
}
let prot = Object.getPrototypeOf(obj);
while (prot !== null) {
if (prot === classFunction.prototype) {
return true;
}
prot = Object.getPrototypeOf(prot);
}
return false;
};
/**
* checkIfInstanceOf(new Date(), Date); // true
*/