Created
October 25, 2020 12:21
-
-
Save Tnifey/367e58a2489fcd587a9341311296aecf to your computer and use it in GitHub Desktop.
Get Prototype Chain From Class Constructor (extends chain)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Ctor } from "./types"; | |
import { isConstructor } from "./utils"; | |
export function chain<T>( | |
ctor: Ctor<T>, | |
prototypes: Set<any> = new Set(), | |
): Ctor<any>[] | Set<Ctor<any>> { | |
if (isConstructor(ctor)) { | |
const target = Object.getPrototypeOf(ctor); | |
if (!target.name || prototypes.has(target)) return prototypes; | |
prototypes.add(target); | |
return chain(target, new Set([...prototypes.values()])); | |
} | |
return [...prototypes.values()]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Ctor<T> = new () => T; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Ctor } from "./types"; | |
export function isConstructor<T>(target: unknown): target is Ctor<T> { | |
try { | |
new (target as any)(); | |
} catch (_err) { | |
return false; | |
} | |
return true; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment