-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmily.js
More file actions
1788 lines (1562 loc) · 54.7 KB
/
Copy pathEmily.js
File metadata and controls
1788 lines (1562 loc) · 54.7 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Emily 1.8.1 http://flams.github.com/emily
*
* The MIT License (MIT)
*
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
*/
/**
* Emily.js - http://flams.github.com/emily/
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Tools',[],
/**
* @class
* Tools is a collection of tools
*/
function Tools(){
/**
* Get the closest number in an array
* @param {Number} item the base number
* @param {Array} array the array to search into
* @param {Function} getDiff returns the difference between the base number and
* and the currently read item in the array. The item which returned the smallest difference wins.
* @private
*/
function _getClosest(item, array, getDiff) {
var closest,
diff;
if (!array) {
return;
}
array.forEach(function (comparedItem, comparedItemIndex) {
var thisDiff = getDiff(comparedItem, item);
if (thisDiff >= 0 && (typeof diff == "undefined" || thisDiff < diff)) {
diff = thisDiff;
closest = comparedItemIndex;
}
});
return closest;
}
return {
/**
* For applications that don't run in a browser, window is not the global object.
* This function returns the global object wherever the application runs.
* @returns {Object} the global object
*/
getGlobal: function getGlobal() {
var func = function() {
return this;
};
return func.call(null);
},
/**
* Mixes an object into another
* @param {Object} source object to get values from
* @param {Object} destination object to mix values into
* @param {Boolean} optional, set to true to prevent overriding
* @returns {Object} the destination object
*/
mixin: function mixin(source, destination, dontOverride) {
this.loop(source, function (value, idx) {
if (!destination[idx] || !dontOverride) {
destination[idx] = source[idx];
}
});
return destination;
},
/**
* Count the number of properties in an object
* It doesn't look up in the prototype chain
* @param {Object} object the object to count
* @returns {Number}
*/
count: function count(object) {
var nbItems = 0;
this.loop(object, function () {
nbItems++;
});
return nbItems;
},
/**
* Compares the properties of two objects and returns true if they're the same
* It's doesn't do it recursively
* @param {Object} first object
* @param {Object} second object
* @returns {Boolean} true if the two objets have the same properties
*/
compareObjects: function compareObjects(object1, object2) {
var getOwnProperties = function (object) {
return Object.getOwnPropertyNames(object).sort().join("");
};
return getOwnProperties(object1) == getOwnProperties(object2);
},
/**
* Compares two numbers and tells if the first one is bigger (1), smaller (-1) or equal (0)
* @param {Number} number1 the first number
* @param {Number} number2 the second number
* @returns 1 if number1>number2, -1 if number2>number1, 0 if equal
*/
compareNumbers: function compareNumbers(number1, number2) {
if (number1>number2) {
return 1;
} else if (number1<number2) {
return -1;
} else {
return 0;
}
},
/**
* Transform array-like objects to array, such as nodeLists or arguments
* @param {Array-like object}
* @returns {Array}
*/
toArray: function toArray(array) {
return [].slice.call(array);
},
/**
* Small adapter for looping over objects and arrays
* Warning: it's not meant to be used with nodeList
* To use with nodeList, convert to array first
* @param {Array/Object} iterated the array or object to loop through
* @param {Function} callback the function to execute for each iteration
* @param {Object} scope the scope in which to execute the callback
* @returns {Boolean} true if executed
*/
loop: function loop(iterated, callback, scope) {
var i,
length;
if (iterated instanceof Object && callback instanceof Function) {
if (iterated instanceof Array) {
for (i=0; i<iterated.length; i++) {
callback.call(scope, iterated[i], i, iterated);
}
} else {
for (i in iterated) {
if (iterated.hasOwnProperty(i)) {
callback.call(scope, iterated[i], i, iterated);
}
}
}
return true;
} else {
return false;
}
},
/**
* Make a diff between two objects
* @param {Array/Object} before is the object as it was before
* @param {Array/Object} after is what it is now
* @example:
* With objects:
*
* before = {a:1, b:2, c:3, d:4, f:6}
* after = {a:1, b:20, d: 4, e: 5}
* will return :
* {
* unchanged: ["a", "d"],
* updated: ["b"],
* deleted: ["f"],
* added: ["e"]
* }
*
* It also works with Arrays:
*
* before = [10, 20, 30]
* after = [15, 20]
* will return :
* {
* unchanged: [1],
* updated: [0],
* deleted: [2],
* added: []
* }
*
* @returns object
*/
objectsDiffs : function objectsDiffs(before, after) {
if (before instanceof Object && after instanceof Object) {
var unchanged = [],
updated = [],
deleted = [],
added = [];
// Look through the after object
this.loop(after, function (value, idx) {
// To get the added
if (typeof before[idx] == "undefined") {
added.push(idx);
// The updated
} else if (value !== before[idx]) {
updated.push(idx);
// And the unchanged
} else if (value === before[idx]) {
unchanged.push(idx);
}
});
// Loop through the before object
this.loop(before, function (value, idx) {
// To get the deleted
if (typeof after[idx] == "undefined") {
deleted.push(idx);
}
});
return {
updated: updated,
unchanged: unchanged,
added: added,
deleted: deleted
};
} else {
return false;
}
},
/**
* Transforms Arrays and Objects into valid JSON
* @param {Object/Array} object the object to JSONify
* @returns the JSONified object or false if failed
*/
jsonify: function jsonify(object) {
if (object instanceof Object) {
return JSON.parse(JSON.stringify(object));
} else {
return false;
}
},
/**
* Clone an Array or an Object
* @param {Array/Object} object the object to clone
* @returns {Array/Object} the cloned object
*/
clone: function clone(object) {
if (object instanceof Array) {
return object.slice(0);
} else if (typeof object == "object" && object !== null && !(object instanceof RegExp)) {
return this.mixin(object, {});
} else {
return false;
}
},
/**
*
*
*
*
* Refactoring needed for the following
*
*
*
*
*
*/
/**
* Get the property of an object nested in one or more objects
* given an object such as a.b.c.d = 5, getNestedProperty(a, "b.c.d") will return 5.
* @param {Object} object the object to get the property from
* @param {String} property the path to the property as a string
* @returns the object or the the property value if found
*/
getNestedProperty: function getNestedProperty(object, property) {
if (object && object instanceof Object) {
if (typeof property == "string" && property !== "") {
var split = property.split(".");
return split.reduce(function (obj, prop) {
return obj && obj[prop];
}, object);
} else if (typeof property == "number") {
return object[property];
} else {
return object;
}
} else {
return object;
}
},
/**
* Set the property of an object nested in one or more objects
* If the property doesn't exist, it gets created.
* @param {Object} object
* @param {String} property
* @param value the value to set
* @returns object if no assignment was made or the value if the assignment was made
*/
setNestedProperty: function setNestedProperty(object, property, value) {
if (object && object instanceof Object) {
if (typeof property == "string" && property !== "") {
var split = property.split(".");
return split.reduce(function (obj, prop, idx) {
obj[prop] = obj[prop] || {};
if (split.length == (idx + 1)) {
obj[prop] = value;
}
return obj[prop];
}, object);
} else if (typeof property == "number") {
object[property] = value;
return object[property];
} else {
return object;
}
} else {
return object;
}
},
/**
* Get the closest number in an array given a base number
* Example: closest(30, [20, 0, 50, 29]) will return 3 as 29 is the closest item
* @param {Number} item the base number
* @param {Array} array the array of numbers to search into
* @returns {Number} the index of the closest item in the array
*/
closest: function closest(item, array) {
return _getClosest(item, array, function (comparedItem, item) {
return Math.abs(comparedItem - item);
});
},
/**
* Get the closest greater number in an array given a base number
* Example: closest(30, [20, 0, 50, 29]) will return 2 as 50 is the closest greater item
* @param {Number} item the base number
* @param {Array} array the array of numbers to search into
* @returns {Number} the index of the closest item in the array
*/
closestGreater: function closestGreater(item, array) {
return _getClosest(item, array, function (comparedItem, item) {
return comparedItem - item;
});
},
/**
* Get the closest lower number in an array given a base number
* Example: closest(30, [20, 0, 50, 29]) will return 0 as 20 is the closest lower item
* @param {Number} item the base number
* @param {Array} array the array of numbers to search into
* @returns {Number} the index of the closest item in the array
*/
closestLower: function closestLower(item, array) {
return _getClosest(item, array, function (comparedItem, item) {
return item - comparedItem;
});
}
};
});
/**
* Emily.js - http://flams.github.com/emily/
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Observable',["Tools"],
/**
* @class
* Observable is an implementation of the Observer design pattern,
* which is also known as publish/subscribe.
*
* This service creates an Observable on which you can add subscribers.
*/
function Observable(Tools) {
/**
* Defines the Observable
* @private
* @returns {_Observable}
*/
return function ObservableConstructor() {
/**
* The list of topics
* @private
*/
var _topics = {};
/**
* Add an observer
* @param {String} topic the topic to observe
* @param {Function} callback the callback to execute
* @param {Object} scope the scope in which to execute the callback
* @returns handle
*/
this.watch = function watch(topic, callback, scope) {
if (typeof callback == "function") {
var observers = _topics[topic] = _topics[topic] || [],
observer = [callback, scope];
observers.push(observer);
return [topic,observers.indexOf(observer)];
} else {
return false;
}
};
/**
* Listen to an event just once before removing the handler
* @param {String} topic the topic to observe
* @param {Function} callback the callback to execute
* @param {Object} scope the scope in which to execute the callback
* @returns handle
*/
this.once = function once(topic, callback, scope) {
var handle = this.watch(topic, function () {
callback.apply(scope, arguments);
this.unwatch(handle);
}, this);
return handle;
};
/**
* Remove an observer
* @param {Handle} handle returned by the watch method
* @returns {Boolean} true if there were subscribers
*/
this.unwatch = function unwatch(handle) {
var topic = handle[0], idx = handle[1];
if (_topics[topic] && _topics[topic][idx]) {
// delete value so the indexes don't move
delete _topics[topic][idx];
// If the topic is only set with falsy values, delete it;
if (!_topics[topic].some(function (value) {
return !!value;
})) {
delete _topics[topic];
}
return true;
} else {
return false;
}
};
/**
* Notifies observers that a topic has a new message
* @param {String} topic the name of the topic to publish to
* @param subject
* @returns {Boolean} true if there was subscribers
*/
this.notify = function notify(topic) {
var observers = _topics[topic],
args = Tools.toArray(arguments).slice(1);
if (observers) {
Tools.loop(observers, function (value) {
try {
if (value) {
value[0].apply(value[1] || null, args);
}
} catch (err) { }
});
return true;
} else {
return false;
}
};
/**
* Check if topic has the described observer
* @param {Handle}
* @returns {Boolean} true if exists
*/
this.hasObserver = function hasObserver(handle) {
return !!( handle && _topics[handle[0]] && _topics[handle[0]][handle[1]]);
};
/**
* Check if a topic has observers
* @param {String} topic the name of the topic
* @returns {Boolean} true if topic is listened
*/
this.hasTopic = function hasTopic(topic) {
return !!_topics[topic];
};
/**
* Unwatch all or unwatch all from topic
* @param {String} topic optional unwatch all from topic
* @returns {Boolean} true if ok
*/
this.unwatchAll = function unwatchAll(topic) {
if (_topics[topic]) {
delete _topics[topic];
} else {
_topics = {};
}
return true;
};
};
});
/**
* Emily.js - http://flams.github.com/emily/
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('StateMachine',["Tools"],
/**
* @class
* Create a stateMachine
*/
function StateMachine(Tools) {
/**
* @param initState {String} the initial state
* @param diagram {Object} the diagram that describes the state machine
* @example
*
* diagram = {
* "State1" : [
* [ message1, action, nextState], // Same as the state's add function
* [ message2, action2, nextState]
* ],
*
* "State2" :
* [ message3, action3, scope3, nextState]
* ... and so on ....
*
* }
*
* @return the stateMachine object
*/
function StateMachineConstructor($initState, $diagram) {
/**
* The list of states
* @private
*/
var _states = {},
/**
* The current state
* @private
*/
_currentState = "";
/**
* Set the initialization state
* @param {String} name the name of the init state
* @returns {Boolean}
*/
this.init = function init(name) {
if (_states[name]) {
_currentState = name;
return true;
} else {
return false;
}
};
/**
* Add a new state
* @private
* @param {String} name the name of the state
* @returns {State} a new state
*/
this.add = function add(name) {
if (!_states[name]) {
var transition = _states[name] = new Transition();
return transition;
} else {
return _states[name];
}
};
/**
* Get an existing state
* @private
* @param {String} name the name of the state
* @returns {State} the state
*/
this.get = function get(name) {
return _states[name];
};
/**
* Get the current state
* @returns {String}
*/
this.getCurrent = function getCurrent() {
return _currentState;
};
/**
* Tell if the state machine has the given state
* @param {String} state the name of the state
* @returns {Boolean} true if it has the given state
*/
this.has = function has(state) {
return _states.hasOwnProperty(state);
};
/**
* Advances the state machine to a given state
* @param {String} state the name of the state to advance the state machine to
* @returns {Boolean} true if it has the given state
*/
this.advance = function advance(state) {
if (this.has(state)) {
_currentState = state;
return true;
} else {
return false;
}
};
/**
* Pass an event to the state machine
* @param {String} name the name of the event
* @returns {Boolean} true if the event exists in the current state
*/
this.event = function event(name) {
var nextState;
nextState = _states[_currentState].event.apply(_states[_currentState].event, Tools.toArray(arguments));
// False means that there's no such event
// But undefined means that the state doesn't change
if (nextState === false) {
return false;
} else {
// There could be no next state, so the current one remains
if (nextState) {
// Call the exit action if any
_states[_currentState].event("exit");
_currentState = nextState;
// Call the new state's entry action if any
_states[_currentState].event("entry");
}
return true;
}
};
/**
* Initializes the StateMachine with the given diagram
*/
Tools.loop($diagram, function (transition, state) {
var myState = this.add(state);
transition.forEach(function (params){
myState.add.apply(null, params);
});
}, this);
/**
* Sets its initial state
*/
this.init($initState);
}
/**
* Each state has associated transitions
* @constructor
*/
function Transition() {
/**
* The list of transitions associated to a state
* @private
*/
var _transitions = {};
/**
* Add a new transition
* @private
* @param {String} event the event that will trigger the transition
* @param {Function} action the function that is executed
* @param {Object} scope [optional] the scope in which to execute the action
* @param {String} next [optional] the name of the state to transit to.
* @returns {Boolean} true if success, false if the transition already exists
*/
this.add = function add(event, action, scope, next) {
var arr = [];
if (_transitions[event]) {
return false;
}
if (typeof event == "string" &&
typeof action == "function") {
arr[0] = action;
if (typeof scope == "object") {
arr[1] = scope;
}
if (typeof scope == "string") {
arr[2] = scope;
}
if (typeof next == "string") {
arr[2] = next;
}
_transitions[event] = arr;
return true;
}
return false;
};
/**
* Check if a transition can be triggered with given event
* @private
* @param {String} event the name of the event
* @returns {Boolean} true if exists
*/
this.has = function has(event) {
return !!_transitions[event];
};
/**
* Get a transition from it's event
* @private
* @param {String} event the name of the event
* @return the transition
*/
this.get = function get(event) {
return _transitions[event] || false;
};
/**
* Execute the action associated to the given event
* @param {String} event the name of the event
* @param {params} params to pass to the action
* @private
* @returns false if error, the next state or undefined if success (that sounds weird)
*/
this.event = function event(newEvent) {
var _transition = _transitions[newEvent];
if (_transition) {
_transition[0].apply(_transition[1], Tools.toArray(arguments).slice(1));
return _transition[2];
} else {
return false;
}
};
}
return StateMachineConstructor;
});
/**
* Emily.js - http://flams.github.com/emily/
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Promise',["Observable", "StateMachine"],
/**
* @class
* Create a promise/A+
*/
function Promise(Observable, StateMachine) {
return function PromiseConstructor() {
/**
* The fulfilled value
* @private
*/
var _value = null,
/**
* The rejection reason
* @private
*/
_reason = null,
/**
* The funky observable
* @private
*/
_observable = new Observable(),
/**
* The state machine States & transitions
* @private
*/
_states = {
// The promise is pending
"Pending": [
// It can only be fulfilled when pending
["fulfill", function onFulfill(value) {
_value = value;
_observable.notify("fulfill", value);
// Then it transits to the fulfilled state
}, "Fulfilled"],
// it can only be rejected when pending
["reject", function onReject(reason) {
_reason = reason;
_observable.notify("reject", reason);
// Then it transits to the rejected state
}, "Rejected"],
// When pending, add the resolver to an observable
["toFulfill", function toFulfill(resolver) {
_observable.watch("fulfill", resolver);
}],
// When pending, add the resolver to an observable
["toReject", function toReject(resolver) {
_observable.watch("reject", resolver);
}]],
// When fulfilled,
"Fulfilled": [
// We directly call the resolver with the value
["toFulfill", function toFulfill(resolver) {
setTimeout(function () {
resolver(_value);
}, 0);
}]],
// When rejected
"Rejected": [
// We directly call the resolver with the reason
["toReject", function toReject(resolver) {
setTimeout(function () {
resolver(_reason);
}, 0);
}]]
},
/**
* The stateMachine
* @private
*/
_stateMachine = new StateMachine("Pending", _states);
/**
* Fulfilled the promise.
* A promise can be fulfilld only once.
* @param the fulfillment value
* @returns the promise
*/
this.fulfill = function fulfill(value) {
_stateMachine.event("fulfill", value);
return this;
};
/**
* Reject the promise.
* A promise can be rejected only once.
* @param the rejection value
* @returns true if the rejection function was called
*/
this.reject = function reject(reason) {
_stateMachine.event("reject", reason);
return this;
};
/**
* The callbacks to call after fulfillment or rejection
* @param {Function} fulfillmentCallback the first parameter is a success function, it can be followed by a scope
* @param {Function} the second, or third parameter is the rejection callback, it can also be followed by a scope
* @examples:
*
* then(fulfillment)
* then(fulfillment, scope, rejection, scope)
* then(fulfillment, rejection)
* then(fulfillment, rejection, scope)
* then(null, rejection, scope)
* @returns {Promise} the new promise
*/
this.then = function then() {
var promise = new PromiseConstructor();
// If a fulfillment callback is given
if (arguments[0] instanceof Function) {
// If the second argument is also a function, then no scope is given
if (arguments[1] instanceof Function) {
_stateMachine.event("toFulfill", this.makeResolver(promise, arguments[0]));
} else {
// If the second argument is not a function, it's the scope
_stateMachine.event("toFulfill", this.makeResolver(promise, arguments[0], arguments[1]));
}
} else {
// If no fulfillment callback given, give a default one
_stateMachine.event("toFulfill", this.makeResolver(promise, function () {
promise.fulfill(_value);
}));
}
// if the second arguments is a callback, it's the rejection one, and the next argument is the scope
if (arguments[1] instanceof Function) {
_stateMachine.event("toReject", this.makeResolver(promise, arguments[1], arguments[2]));
}
// if the third arguments is a callback, it's the rejection one, and the next arguments is the sopce
if (arguments[2] instanceof Function) {
_stateMachine.event("toReject", this.makeResolver(promise, arguments[2], arguments[3]));
}
// If no rejection callback is given, give a default one
if (!(arguments[1] instanceof Function) &&
!(arguments[2] instanceof Function)) {
_stateMachine.event("toReject", this.makeResolver(promise, function () {
promise.reject(_reason);
}));
}
return promise;
};
/**
* Synchronize this promise with a thenable
* @returns {Boolean} false if the given sync is not a thenable
*/
this.sync = function sync(syncWith) {
if (syncWith instanceof Object && syncWith.then) {
var onFulfilled = function onFulfilled(value) {
this.fulfill(value);
},
onRejected = function onRejected(reason) {
this.reject(reason);
};
syncWith.then(onFulfilled.bind(this),
onRejected.bind(this));
return true;
} else {
return false;
}
};
/**
* Make a resolver
* for debugging only
* @private
* @returns {Function} a closure
*/
this.makeResolver = function makeResolver(promise, func, scope) {
return function resolver(value) {
var returnedPromise;
try {
returnedPromise = func.call(scope, value);
if (!promise.sync(returnedPromise)) {
promise.fulfill(returnedPromise);
}
} catch (err) {
promise.reject(err);
}
};
};