Skip to content

Commit 809424b

Browse files
committed
support referencing functions by name
1 parent 2af5fa9 commit 809424b

File tree

4 files changed

+21
-7
lines changed

4 files changed

+21
-7
lines changed

.travis.yml

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ before_script:
44
node_js:
55
- "4"
66
- "5"
7+
- "6"
78
after_script:
89
- codeclimate-test-reporter < coverage/lcov.info
910
- coveralls < coverage/lcov.info

lib/evaluation.js

+1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ function Evaluation(js, script, data, refPrefix) {
1111
this.refPrefixRegexp = new RegExp('^' + refPrefix);
1212
this.evaluatedRefs = {};
1313
this.pendingRefs = {};
14+
this.functions = {};
1415
}

lib/instruction_keywords.js

+17-5
Original file line numberDiff line numberDiff line change
@@ -144,15 +144,27 @@ function eval$delay(params) {
144144
* @return {Function} Function that returns Script or synchronous/asynchronous value
145145
*/
146146
function eval$func(params) {
147+
var funcBody = params.$func;
148+
if (typeof funcBody == 'string') {
149+
if (Object.keys(params).length > 1)
150+
throw new Error('reference to function "' + funcBody + '" has other properties');
151+
if (!(funcBody in this.functions))
152+
throw new Error('unknown function "' + funcBody + '"');
153+
return this.functions[funcBody];
154+
}
155+
147156
var self = this;
148-
var valid = this.js.validate(params.$func);
149-
if (valid) return Promise.resolve(func);
150-
var err = this.js.ajv.ValidationError(this.js.validate.errors);
151-
return Promise.reject(err);
157+
var valid = this.js.validate(funcBody);
158+
if (valid) {
159+
var pFunc = Promise.resolve(func);
160+
if (params.$name) this.functions[params.$name] = pFunc;
161+
return pFunc;
162+
}
163+
throw new this.js.ajv.ValidationError(this.js.validate.errors);
152164

153165
function func() {
154166
var data = params.$args ? prepareArguments(arguments) : self.data;
155-
var script = JSON.parse(JSON.stringify(params.$func));
167+
var script = JSON.parse(JSON.stringify(funcBody));
156168
return self.js.evaluate(script, data);
157169
}
158170

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@
3636
"coveralls": "^2.11.6",
3737
"eslint": "^2.2.0",
3838
"istanbul": "^0.4.2",
39-
"jsonscript-test": "^0.2.0",
40-
"jsonscript-test-suite": "^0.2.1",
39+
"jsonscript-test": "^0.2.1",
40+
"jsonscript-test-suite": "^0.2.2",
4141
"mocha": "^2.4.5",
4242
"pre-commit": "^1.1.2"
4343
}

0 commit comments

Comments
 (0)