Skip to content

Commit 26beaf3

Browse files
committed
feat: prototype-traversal of 2618 added
1 parent 9155678 commit 26beaf3

File tree

6 files changed

+121
-22
lines changed

6 files changed

+121
-22
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# LeetCode JavaScript
22

3-
> JavaScript-only LeetCode questions with solutions, explanations, and concept-based tagging.
3+
> JavaScript-only LeetCode questions with solutions, and explanations.
44
55
---

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
"@eslint/js": "^9.31.0",
4242
"@types/jest": "^30.0.0",
4343
"@types/node": "^24.1.0",
44+
"chalk": "^5.4.1",
4445
"eslint": "^9.31.0",
4546
"globals": "^16.3.0",
4647
"husky": "^9.1.7",

pnpm-lock.yaml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 53 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,58 @@
1-
import { checkIfInstanceOf } from '@/app/2618-check-if-object-instance-of-class'
1+
import {
2+
checkIfInstanceOf,
3+
checkIfInstanceOfUsingPrototype,
4+
} from '@/app/2618-check-if-object-instance-of-class'
25

36
describe('Problem 2618: Check If Instance Of Class', () => {
4-
test('Example 1: new Date() is an instance of Date', () => {
5-
expect(checkIfInstanceOf(new Date(), Date)).toBe(true)
6-
})
7-
8-
test('Example 2: Dog is an instance of Animal', () => {
9-
class Animal {}
10-
class Dog extends Animal {}
11-
expect(checkIfInstanceOf(new Dog(), Animal)).toBe(true)
12-
})
13-
14-
test('Example 3: Date constructor is not an instance of Date', () => {
15-
expect(checkIfInstanceOf(Date, Date)).toBe(false)
16-
})
7+
const testCases: {
8+
name: string
9+
input: [any, any]
10+
expected: boolean
11+
}[] = [
12+
{
13+
name: 'Example 1: new Date() is an instance of Date',
14+
input: [new Date(), Date],
15+
expected: true,
16+
},
17+
{
18+
name: 'Example 2: Dog is an instance of Animal',
19+
input: (() => {
20+
class Animal {}
21+
class Dog extends Animal {}
22+
return [new Dog(), Animal] as [any, any]
23+
})(),
24+
expected: true,
25+
},
26+
{
27+
name: 'Example 3: Date constructor is not an instance of Date',
28+
input: [Date, Date],
29+
expected: false,
30+
},
31+
{
32+
name: 'Example 4: Primitive 5 is an instance of Number (via wrapper)',
33+
input: [5, Number],
34+
expected: true,
35+
},
36+
{
37+
name: 'Edge case: null value should return false',
38+
input: [null, Number],
39+
expected: false,
40+
},
41+
{
42+
name: 'Edge case: undefined classFunction should return false',
43+
input: [new Number(5), undefined],
44+
expected: false,
45+
},
46+
]
1747

18-
test('Example 4: Primitive 5 is an instance of Number (via wrapper)', () => {
19-
expect(checkIfInstanceOf(5, Number)).toBe(true)
48+
describe.each([
49+
['🔍 instanceof version', checkIfInstanceOf],
50+
['🔁 prototype-traversal version', checkIfInstanceOfUsingPrototype],
51+
])('%s', (_label, fn) => {
52+
testCases.forEach(({ name, input, expected }) => {
53+
test(name, () => {
54+
expect(fn(...input)).toBe(expected)
55+
})
56+
})
2057
})
2158
})

src/app/2618-check-if-object-instance-of-class.ts

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// * Title
22
// 2618. Check if Object Instance of Class
33

4+
// * Concepts
5+
// Prototype Chain, Inheritance, instanceof, Type Checking
6+
47
// * Description
58
/**
69
*
@@ -26,18 +29,52 @@
2629

2730
// * Solution
2831
function checkIfInstanceOf(obj: any, classFunction: any): boolean {
32+
// If obj is null or undefined, it can't be an instance of anything
2933
if (obj === null || obj === undefined) return false
3034

35+
// If classFunction is not a function (i.e., not a constructor), return false
3136
if (typeof classFunction !== 'function') return false
3237

38+
// If the object is already an instance of the class, return true
3339
if (obj instanceof classFunction) return true
3440

41+
// Try converting the value to an object and check again using instanceof
42+
// This handles edge cases like primitives (e.g., number, string)
3543
try {
3644
return Object(obj) instanceof classFunction
3745
} catch {
46+
// If conversion or check fails (e.g., invalid input), return false
3847
return false
3948
}
4049
}
4150

51+
function checkIfInstanceOfUsingPrototype(obj: any, classFunction: any): boolean {
52+
// Return false if the input value is null or undefined
53+
if (obj === null || obj === undefined) return false
54+
55+
// Return false if the classFunction is not a function (constructor)
56+
if (typeof classFunction !== 'function') return false
57+
58+
// Get the prototype that we're trying to match
59+
const targetPrototype = classFunction.prototype
60+
61+
// Convert obj to an object (handles primitives like numbers, strings, etc.)
62+
let currentProto = Object(obj)
63+
64+
// Traverse up the prototype chain
65+
while (currentProto !== null) {
66+
// If the prototype matches the target, return true
67+
if (Object.getPrototypeOf(currentProto) === targetPrototype) {
68+
return true
69+
}
70+
71+
// Move one level up the prototype chain
72+
currentProto = Object.getPrototypeOf(currentProto)
73+
}
74+
75+
// If we reach the end of the chain without a match, return false
76+
return false
77+
}
78+
4279
// * Export the function
43-
export { checkIfInstanceOf }
80+
export { checkIfInstanceOf, checkIfInstanceOfUsingPrototype }

src/main.ts

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,30 @@
1-
import { checkIfInstanceOf } from '@/app/2618-check-if-object-instance-of-class'
1+
import chalk from 'chalk'
22

33
function main() {
4-
console.log('Hello, World!')
5-
const dateInstance = new Date()
6-
console.log(checkIfInstanceOf(dateInstance, Date)) // true
4+
console.clear()
5+
console.log(
6+
chalk.green.bold('\n🚀 Welcome to ') + chalk.blueBright.bold('LeetCode JavaScript Practice!\n'),
7+
)
8+
9+
console.log(
10+
chalk.gray('📚 This is a curated collection of LeetCode problems with:') +
11+
'\n' +
12+
chalk.cyan(' • JavaScript-only solutions') +
13+
'\n' +
14+
chalk.cyan(' • Clear explanations') +
15+
'\n' +
16+
chalk.cyan(' • Concept-based tagging for deep learning\n'),
17+
)
18+
19+
console.log(
20+
chalk.yellow('✨ Run ') +
21+
chalk.magenta('pnpm test') +
22+
chalk.yellow(' to test all problems or ') +
23+
chalk.magenta('pnpm test:problem') +
24+
chalk.yellow(' to run a specific one.\n'),
25+
)
26+
27+
console.log(chalk.green('Happy coding! 💻\n'))
728
}
829

930
main()

0 commit comments

Comments
 (0)