Skip to content

Instantly share code, notes, and snippets.

@Tnifey
Created October 25, 2020 12:21
Show Gist options
  • Save Tnifey/367e58a2489fcd587a9341311296aecf to your computer and use it in GitHub Desktop.
Save Tnifey/367e58a2489fcd587a9341311296aecf to your computer and use it in GitHub Desktop.
Get Prototype Chain From Class Constructor (extends chain)
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()];
}
export type Ctor<T> = new () => T;
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