1 |
|
2 |
|
3 |
|
4 |
|
5 | (function(define) { 'use strict';
|
6 | define(function(require) {
|
7 |
|
8 | var when = require('./when');
|
9 | var slice = Array.prototype.slice;
|
10 |
|
11 | |
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function lift(generator) {
|
18 | return function() {
|
19 | return run(generator, this, arguments);
|
20 | };
|
21 | }
|
22 |
|
23 | |
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | function call(generator /*x, y, z...*/) {
|
33 |
|
34 | return run(generator, this, slice.call(arguments, 1));
|
35 | }
|
36 |
|
37 | |
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | function apply(generator, args) {
|
47 |
|
48 | return run(generator, this, args || []);
|
49 | }
|
50 |
|
51 | |
52 |
|
53 |
|
54 |
|
55 | function run(generator, thisArg, args) {
|
56 | var stepper = new Stepper(next, error, generator.apply(thisArg, args));
|
57 |
|
58 | return stepper.step('next', void 0);
|
59 |
|
60 | function next(x) { return stepper.step('next', x); }
|
61 | function error(e) { return stepper.step('throw', e); }
|
62 | }
|
63 |
|
64 | |
65 |
|
66 |
|
67 |
|
68 | function Stepper(next, error, iterator) {
|
69 | this.next = next;
|
70 | this.error = error;
|
71 | this.iterator = iterator;
|
72 | }
|
73 |
|
74 | Stepper.prototype.step = function(action, x) {
|
75 | try {
|
76 | return this._continue(action, x);
|
77 | } catch (e) {
|
78 | return when.reject(e);
|
79 | }
|
80 | };
|
81 |
|
82 | Stepper.prototype._continue = function(action, x) {
|
83 | var result = this.iterator[action](x);
|
84 | return result.done ? result.value : when(result.value, this.next, this.error);
|
85 | };
|
86 |
|
87 | return {
|
88 | lift: lift,
|
89 | call: call,
|
90 | apply: apply
|
91 | };
|
92 |
|
93 | });
|
94 | }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
|