Skip to content

Commit

Permalink
wrote code
Browse files Browse the repository at this point in the history
  • Loading branch information
Ramakrishna committed Dec 20, 2017
1 parent 9fadf5b commit 779b611
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
42 changes: 42 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'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)
}
}

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 config;
});
} else {
global = (function () {
return this || (0, eval)('this');
}());
global.overrideFunction = overrideFunction
}
23 changes: 23 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict'
const functionOverride = require('./index')

const res = {
send: function(...args){
console.log(`res.send called with arguments -- ${args} -- and context ${JSON.stringify(this)}`)
},
a: 1
}

function before(...args){
console.log(`before called with arguments -- ${args} -- and context ${JSON.stringify(this)}`)
}

function after(...args) {
console.log(`after called with arguments -- ${args} -- and context ${JSON.stringify(this)}`)
}

before = before.bind(this, "before", "fdsfsdfdsfsdfdsfds")

res.send = functionOverride(res, 'send', {before, after})

res.send("dsa", "sfds")

0 comments on commit 779b611

Please sign in to comment.