Skip to content

Commit 6cd3898

Browse files
author
Jack Ellis
committed
feat: encase static method
1 parent 9b18954 commit 6cd3898

4 files changed

Lines changed: 43 additions & 1 deletion

File tree

changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Change Log
44
- if an option in the `properties` config is null, jpex will no longer throw an error
55
- Passing `$options` into a `Jpex as a Service` service now works
66
- `Jpex.register.service().bindToInstance()` allows you to bind dependencies to a service instance
7+
- `Jpex.$encase` method allos you to wrap a function with a number of dependencies
78

89
## 2.0.0
910
### Features

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "jpex",
3-
"version": "2.0.0",
3+
"version": "2.1.0",
44
"description": "Javascript Prototype Extension",
55
"main": "src/index.js",
66
"directories": {

spec/class/encase.spec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
describe('encase', function(){
2+
var Jpex;
3+
beforeEach(function () {
4+
Jpex = require('../../src').extend();
5+
});
6+
7+
it('should encase a method with specified dependencies', function () {
8+
Jpex.register.constant('FOO', 'injected');
9+
const fn = Jpex.$encase([ 'FOO' ], (foo) => (bah) => (foo + bah));
10+
11+
const result = fn('provided');
12+
13+
expect(result).toBe('injectedprovided');
14+
});
15+
16+
it('infers dependencies from function arguments', function () {
17+
Jpex.register.constant('FOO', 'injected');
18+
const fn = Jpex.$encase((FOO) => (bah) => (FOO + bah));
19+
20+
const result = fn('provided');
21+
22+
expect(result).toBe('injectedprovided');
23+
});
24+
});

src/class/privates.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,20 @@ function resolve(name, namedParameters) {
6161
resolver.resolve(this, name, namedParameters);
6262
}
6363

64+
function encase(dependencies, fn) {
65+
var self = this;
66+
if (typeof dependencies === 'function') {
67+
fn = dependencies;
68+
dependencies = resolver.extractParameters(fn);
69+
}
70+
return function () {
71+
var context = this;
72+
var args = Array.prototype.slice.call(arguments);
73+
var deps = self.$resolve(dependencies);
74+
return fn.apply(context, deps).apply(context, args);
75+
};
76+
}
77+
6478
function clearCache(names) {
6579
names = names ? [].concat(names) : [];
6680
var key;
@@ -85,6 +99,9 @@ module.exports = function (Parent, Class, options) {
8599
$resolve : {
86100
value : resolve
87101
},
102+
$encase: {
103+
value: encase,
104+
},
88105
$clearCache : {
89106
value : clearCache
90107
},

0 commit comments

Comments
 (0)