-
Notifications
You must be signed in to change notification settings - Fork 0
/
function-override.js
47 lines (45 loc) · 1.47 KB
/
function-override.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
'use strict'
function _callFunc(self, obj, args){
const fn = typeof obj === 'function' ? obj : obj.function
if(typeof fn !== 'function') {
return
}
let functionArguments = obj.args
const context = obj.ignoreContext ? undefined : self
if(!functionArguments){
functionArguments = Array.from(args)
}
if(typeof functionArguments === 'object' && functionArguments.constructor === Array) {
fn.apply(context, functionArguments)
}
}
/**
* @param {object} self The context in which the function is executed
* @param {function} functionToReplace The function which should be replaced
* @param {options} options Options
*/
function overrideFunction(self, functionToReplace, {before, after}) {
const oldFunc = self[functionToReplace]
if(typeof oldFunc !== 'function'){
throw new Error('Original function not provided')
}
const newFunc = function(...args){
_callFunc(self, before, args)
oldFunc.apply(self, args)
_callFunc(self, after, args)
}
self[functionToReplace] = newFunc
return newFunc
}
if(typeof module !== 'undefined' && module.exports){
module.exports = overrideFunction
} else if (typeof define === 'function' && define.amd) {
define(function () {
return overrideFunction
})
} else {
global = (function () {
return this || (0, eval)('this')
}())
global.overrideFunction = overrideFunction
}