Last active
February 28, 2021 04:42
-
-
Save jonrandy/1305949964ba71fe4051d6a2cfcd6f6f to your computer and use it in GitHub Desktop.
Function Decoration Idea in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function decorating in JS | |
function ___(wrapper) { | |
return function wrap(f) { | |
let a = { [f.name] : function(...args) {return wrapper.call(this, f, ...args)} } | |
return this[f.name] = a[f.name] | |
} | |
} | |
function $__(inner) { | |
return ___(function(main, ...args) { | |
let newargs | |
newargs=inner.call(this, ...args) | |
if (newargs !== undefined) args = Array.isArray(newargs) ? newargs : [newargs] | |
return main.call(this, ...args) | |
}) | |
} | |
function __$(inner) { | |
return ___(function(main, ...args) { | |
let res = main.call(this, ...args) | |
inner.call(this, ...args) | |
return res | |
}) | |
} | |
let log = (...args)=>{ | |
console.log('Log:'), | |
console.log(args) | |
//return args.map(x=>x+'(logged)') | |
} | |
__$(log)( | |
function greet(name) { | |
console.log('Hello '+name+'!') | |
} | |
) | |
greet('Jon') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment