Created
March 23, 2017 18:41
-
-
Save BTMPL/f95367f7ee1dcc393848395557ab6795 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 test(params) { | |
return { | |
type: 'TEST', | |
payload: params | |
} | |
} | |
const metaizeThis = (fn) => { | |
fn._meta = {}; | |
fn.addMeta = function(meta) { | |
if(!this._originalFunction) { | |
this._originalFunction = this; | |
this._originalFunction._meta = {}; | |
} | |
this._originalFunction._meta = {...this._originalFunction._meta, ...meta} | |
const wrapped = (...params) => { | |
const result = this(...params); | |
result.meta = {...this._meta,...meta}; | |
return result | |
} | |
wrapped.addMeta = this.addMeta; | |
wrapped._originalFunction = this._originalFunction; | |
wrapped._meta = this._originalFunction._meta; | |
return wrapped; | |
} | |
return fn; | |
} | |
const wm = metaizeThis(test).addMeta({test: 1}).addMeta({ook: 2}).addMeta({lue: 42}); | |
const wm2 = metaizeThis(test).addMeta({um: 1}).addMeta({oooohThisIsBad: true}); | |
console.log(wm(1)); | |
console.log(wm2(1)); | |
/* | |
Object { | |
"meta": Object { | |
"lue": 42, | |
"ook": 2, | |
"test": 1 | |
}, | |
"payload": 1, | |
"type": "TEST" | |
} | |
Object { | |
"meta": Object { | |
"oooohThisIsBad": true, | |
"um": 1 | |
}, | |
"payload": 1, | |
"type": "TEST" | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is going on here? I'm going to try and decipher this over the weekend, but I would love some commentary from you.