Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/python/python-wasm/src/util.ts
1067 views
1
// I wrote this in packages/util/misc in cocalc and copied it here. -- William Stein
2
3
// Get *all* methods of an object (including from base classes!).
4
// See https://flaviocopes.com/how-to-list-object-methods-javascript/
5
// This is used by bind_methods below to bind all methods
6
// of an instance of an object, all the way up the
7
// prototype chain, just to be 100% sure!
8
function get_methods(obj: object): string[] {
9
let properties = new Set<string>();
10
let current_obj = obj;
11
do {
12
Object.getOwnPropertyNames(current_obj).map((item) => properties.add(item));
13
} while ((current_obj = Object.getPrototypeOf(current_obj)));
14
return [...properties.keys()].filter(
15
(item) => typeof obj[item] === "function"
16
);
17
}
18
19
// Bind all or specified methods of the object. If method_names
20
// is not given, binds **all** methods.
21
// For example, in a base class constructor, you can do
22
// bind_methods(this);
23
// and every method will always be bound even for derived classes
24
// (assuming they call super if they overload the constructor!).
25
// Do this for classes that don't get created in a tight inner
26
// loop and for which you want 'safer' semantics.
27
export function bind_methods<T extends object>(
28
obj: T,
29
method_names: undefined | string[] = undefined
30
): T {
31
if (method_names === undefined) {
32
method_names = get_methods(obj);
33
method_names.splice(method_names.indexOf("constructor"), 1);
34
}
35
for (const method_name of method_names) {
36
obj[method_name] = obj[method_name].bind(obj);
37
}
38
return obj;
39
}
40
41