-
Notifications
You must be signed in to change notification settings - Fork 0
/
hijack.js
68 lines (63 loc) · 1.51 KB
/
hijack.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Simple hijacking utility.
*
* Simple utility to hijack object methods. By not bothering with error checking
* (e.g.: Does the object exist? Does the method exist?), as well as only
* dealing with methods or getters (setters are not supported), nor with
* stacking or pattern matching, we can keep this simple and small.
*
* The function returns a hijack object, which can be used to restore the
* original method implementation.
*
* No return value stacking or pattern matching is supported; it's up to the
* caller to implement those.
*
* @module jsutils/wunit/hijack
*/
function hijack(obj, method, implem) {
const {
configurable,
enumerable,
get,
writable,
value,
} = Object.getOwnPropertyDescriptor(obj, method);
const isGetter = get !== undefined;
if (isGetter) {
Object.defineProperty(obj, method, {
configurable,
enumerable,
get: () => {
return implem.apply(obj);
},
});
} else {
Object.defineProperty(obj, method, {
configurable,
enumerable,
writable: false,
value: (...args) => {
return implem.apply(obj, args);
},
});
}
return {
restore() {
if (isGetter) {
Object.defineProperty(obj, method, {
configurable,
enumerable,
get,
});
} else {
Object.defineProperty(obj, method, {
configurable,
enumerable,
writable,
value,
});
}
},
};
}
module.exports = hijack;