/
with_dsl_new_function.js
51 lines (39 loc) · 1.01 KB
/
with_dsl_new_function.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
if (typeof print === 'undefined') {
print = alert;
}
var DSLRunner = {
ingredients: [],
prepareFunctionBody: function(fn) {
return '(' + fn.toString().replace(/\s+$/, '') + ')()';
},
withDSL: function(callback) {
var body = this.prepareFunctionBody(callback),
f = new Function('bake', 'addIngredient', body),
args = [this.bake, this.addIngredient];
return function() { f.apply(this, args); };
},
run: function(definition) {
this.withDSL(definition)();
print("Your specified ingredients included: " + this.ingredients.join(', '));
},
bake: function(callback) {
callback.call(this);
},
addIngredient: function(ingredient) {
DSLRunner.ingredients.push(ingredient);
},
last: function(callback) {
callback.call(this);
}
};
DSLRunner.run(function() {
bake(function() {
addIngredient('flour');
addIngredient('yeast');
addIngredient('water');
print("Baking bread");
});
bake(function() {
print("Baking a cake");
});
});