Created
June 6, 2016 21:55
-
-
Save idmontie/ded17bcf67281172d7f4484a65513dfb to your computer and use it in GitHub Desktop.
Simple function injection
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
export default function inject() { | |
const args = [...arguments]; | |
const toCall = args[0]; | |
const toInject = args.slice(1, args.length); | |
const shouldInject = inject.should === false ? false : true; | |
if (shouldInject) { | |
return function () { | |
const combinedArgs = [...toInject, ...arguments]; | |
return toCall.apply(this, combinedArgs); | |
}; | |
} | |
else { | |
return toCall; | |
} | |
} |
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
import { expect } from 'chai'; | |
import inject from '../inject'; | |
const { describe, it } = global; | |
describe('inject utility', () => { | |
const adder = (a, b, c) => { | |
return a + b + c; | |
}; | |
const caller = (a, b) => { | |
return a(b); | |
}; | |
it('can inject a dependency without changing the parameters', () => { | |
const useDeps = inject(adder, 1); | |
expect( | |
useDeps(2, 3) | |
).to.be.equal(6); | |
}); | |
it('can inject functions', () => { | |
const useDeps = inject(caller, (a) => { return a * 2; }); | |
expect( | |
useDeps(4) | |
).to.be.equal(8); | |
}); | |
it('can be disabled', () => { | |
inject.should = false; | |
const useDeps = inject(caller, (a) => { return a * 2; }); | |
expect( | |
useDeps(a => { return a * 4; }, 4) | |
).to.be.equal(16); | |
inject.should = true; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment