-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminno-sequencer.js
1139 lines (898 loc) · 33.4 KB
/
minno-sequencer.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
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('lodash')) :
typeof define === 'function' && define.amd ? define(['lodash'], factory) :
(global['minno-sequencer'] = factory(global._));
}(this, (function (_) { 'use strict';
_ = _ && _.hasOwnProperty('default') ? _['default'] : _;
/**
* A function that maps a mixer object into a sequence.
*
* The basic structure of such an obect is:
* {
* mixer: 'functionType',
* remix : false,
* data: [task1, task2]
* }
*
* The results of the mix are set into `$parsed` within the original mixer object.
* if remix is true $parsed is returned instead of recomputing
*
* @param {Object} [obj] [a mixer object]
* @returns {Array} [An array of mixed objects]
*/
mixProvider.$inject = ['randomizeShuffle', 'randomizeRandom'];
function mixProvider(shuffle, random){
function mix(obj){
var mixerName = obj.mixer;
// if this isn't a mixer
// make sure we catch mixers that are set with undefined by accident...
if (!(_.isPlainObject(obj) && 'mixer' in obj)) return [obj];
if (_.isUndefined(mix.mixers[mixerName])) throw new Error('Mixer: unknow mixer type = ' + mixerName);
if (!obj.remix && obj.$parsed) return obj.$parsed;
obj.$parsed = mix.mixers[mixerName].apply(null, arguments);
if (!_.isArray(obj.$parsed)) throw new Error('Mixer: mixers must return an array (mixer: ' + mixerName + ')');
return obj.$parsed;
}
function deepMixer(sequence, context){
return _.reduce(sequence, function(arr,value){
if (_.isPlainObject(value) && 'mixer' in value && value.mixer != 'wrapper' && !value.wrapper){
var seq = deepMixer(mix(value, context), context);
return arr.concat(seq);
} else {
return arr.concat([value]);
}
}, []);
}
mix.mixers = {
wrapper : function(obj){
return obj.data;
},
repeat: function(obj){
var sequence = obj.data || [];
var result = [], i;
for (i=0; i < obj.times; i++){
result = result.concat(_.cloneDeep(sequence));
}
return result;
},
// randomize any elements
random: function(obj, context){
var sequence = obj.data ? deepMixer(obj.data, context) : [];
return shuffle(sequence);
},
choose: function(obj, context){
var sequence = obj.data ? deepMixer(obj.data, context) : [];
return _.take(shuffle(sequence), obj.n ? obj.n : 1);
},
custom: function(obj, context){
return _.isFunction(obj.fn) ? obj.fn(obj, context) : [];
},
weightedRandom: weightedChoose,
weightedChoose: weightedChoose
};
return mix;
function weightedChoose(obj, context){
var sequence = obj.data ? deepMixer(obj.data, context) : [];
var n = obj.n || 1;
var total_weight = _.sum(obj.weights);
if (!_.isArray(obj.weights)) throw new Error('Mixer: weightedRandom requires an array of weights');
return _.range(0,n)
.map(generate)
.map(_.clone);
function generate(){
var i;
var random_num = random() * total_weight; // cutoff - when we reach this sum - we've reached the desired weight
var weight_sum = 0;
for (i = 0; i < sequence.length; i++) {
weight_sum += obj.weights[i];
weight_sum = +weight_sum.toFixed(3);
if (random_num <= weight_sum) return obj.data[i];
}
throw new Error('Mixer: something went wrong with weightedRandom');
}
}
}
mixerDotNotationProvider$1.$inject = ['dotNotation'];
function mixerDotNotationProvider$1(dotNotation){
function mixerDotNotation(chain, obj){
var escapeSeparatorRegex= /[^/]\./;
if (!_.isString(chain)) return chain;
// We do not have a non escaped dot: we treat this as a string
if (!escapeSeparatorRegex.test(chain)) return chain.replace('/.','.');
return dotNotation(chain, obj);
}
return mixerDotNotation;
}
mixerConditionProvider$1.$inject = ['mixerDotNotation','piConsole'];
function mixerConditionProvider$1(dotNotation,piConsole){
var operatorHash = {
gt: forceNumeric(_.gt),
greaterThan: forceNumeric(_.gt),
gte: forceNumeric(_.gte),
greaterThanOrEqual: forceNumeric(_.gte),
lt: forceNumeric(_.lt),
lesserThan: forceNumeric(_.lt),
lte: forceNumeric(_.lte),
lesserThanOrEqual: forceNumeric(_.lte),
equals: _.isEqual,
'in': _.rearg(_.includes,1,0), // effectively reverse
contains: _.rearg(_.includes,1,0), // effectively reverse
exactly: exactly,
isTruthy: isTruthy
};
function mixerCondition(condition, context){
var operator = getOperator(condition);
var left = dotNotation(condition.compare,context);
var right = dotNotation(condition.to,context);
if (condition.DEBUG) piConsole({
type:'info',
message:'Condition info',
rows: [
['Left: ', left],
['Operator: ', condition.operator || 'equals'],
['Right: ', right]
],
context: condition,
});
return condition.negate
? !operator.apply(context,[left, right, context])
: operator.apply(context,[left, right, context]);
}
return mixerCondition;
// extract the operator function from the condition
function getOperator(condition){
var operator = condition.operator;
if (_.isFunction(condition)) return condition;
if (!_.has(condition, 'operator')) return _.has(condition,'to') ? _.isEqual : isTruthy;
if (_.isFunction(operator)) return operator;
return operatorHash[operator];
}
function isTruthy(left){ return !!left; }
function exactly(left,right){ return left === right;}
function forceNumeric(cb){ return function(left,right){ return [left,right].every(_.isNumber) ? cb(left,right) : false; }; }
}
evaluateProvider.$inject = ['mixerCondition'];
function evaluateProvider(condition){
/**
* Checks if a conditions set is true
* @param {Array} conditions [an array of conditions]
* @param {Object} context [A context for the condition checker]
* @return {Boolean} [Are these conditions true]
*/
function evaluate(conditions,context){
// make && the default
_.isArray(conditions) && (conditions = {and:conditions});
function test(cond){return evaluate(cond,context);}
// && objects
if (conditions.and){
return _.every(conditions.and, test);
}
if (conditions.nand){
return !_.every(conditions.nand, test);
}
// || objects
if (conditions.or){
return _.some(conditions.or, test);
}
if (conditions.nor){
return !_.some(conditions.nor, test);
}
return condition(conditions, context);
}
return evaluate;
}
/**
* Registers the branching mixers with the mixer
* @return {function} [mixer decorator]
*/
mixerBranchingDecorator$1.$inject = ['$delegate','mixerEvaluate','mixerDefaultContext','piConsole'];
function mixerBranchingDecorator$1(mix, evaluate, mixerDefaultContext, piConsole){
mix.mixers.branch = branch;
mix.mixers.multiBranch = multiBranch;
return mix;
/**
* Branching mixer
* @return {Array} [A data array with objects to continue with]
*/
function branch(obj, context){
context = _.extend(context || {}, mixerDefaultContext);
if (_.isUndefined(obj.conditions)) {
piConsole({
type:'error',
message: 'Missing conditions in branch mixer.',
context: obj
});
throw new Error('Missing conditions in branch mixer.');
}
return evaluate(obj.conditions, context) ? obj.data || [] : obj.elseData || [];
}
/**
* multiBranch mixer
* @return {Array} [A data array with objects to continue with]
*/
function multiBranch(obj, context){
context = _.extend(context || {}, mixerDefaultContext);
var row;
row = _.find(obj.branches, function(branch){
if (_.isUndefined(branch.conditions)) {
piConsole({
type:'error',
message: 'Missing conditions in multi branch mixer.',
context: branch
});
throw new Error('Missing conditions in multi branch mixer.');
}
return evaluate(branch.conditions, context);
});
if (row) {
return row.data || [];
}
return obj.elseData || [];
}
}
mixerSequenceProvider$1.$inject = ['mixer'];
function mixerSequenceProvider$1(mix){
/**
* MixerSequence takes an mixer array and allows browsing back and forth within it
* @param {Array} arr [a mixer array]
*/
function MixerSequence(arr){
this.sequence = arr;
this.stack = [];
this.add(arr);
this.pointer = 0;
}
_.extend(MixerSequence.prototype, {
/**
* Add sequence to mixer
* @param {[type]} arr Sequence
* @param {[type]} reverse Whether to start from begining or end
*/
add: function(arr, reverse){
this.stack.push({pointer:reverse ? arr.length : -1,sequence:arr});
},
proceed: function(direction, context){
// get last subSequence
var subSequence = this.stack[this.stack.length-1];
var isNext = (direction === 'next');
// if we ran out of sequence
// add the original sequence back in
if (!subSequence) {
throw new Error ('mixerSequence: subSequence not found');
}
subSequence.pointer += isNext ? 1 : -1;
var el = subSequence.sequence[subSequence.pointer];
// if we ran out of elements, go to previous level (unless we are on the root sequence)
if (_.isUndefined(el) && this.stack.length > 1){
this.stack.pop();
return this.proceed.call(this,direction,context);
}
// if element is a mixer, mix it
if (el && el.mixer){
this.add(mix(el,context), !isNext);
return this.proceed.call(this,direction,context);
}
// regular element or undefined (end of sequence)
return this;
},
next: function(context){
this.pointer++;
return this.proceed.call(this, 'next',context);
},
prev: function(context){
this.pointer--;
return this.proceed.call(this, 'prev',context);
},
/**
* Return current element
* should **never** return a mixer - supposed to abstract them away
* @return {[type]} undefined or element
*/
current:function(){
// get last subSequence
var subSequence = this.stack[this.stack.length-1];
if (!subSequence) {
throw new Error ('mixerSequence: subSequence not found');
}
var el = subSequence.sequence[subSequence.pointer];
if (!el){
return undefined;
}
// extend element with meta data
el.$meta = this.meta();
return el;
},
meta: function(){
return {
number: this.pointer,
// sum of sequence length, minus one (the mixer) for each level of stack except the last
outOf: _.reduce(this.stack, function(memo,sub){return memo + sub.sequence.length-1;},0)+1
};
}
});
return MixerSequence;
}
function dotNotation$1(chain, obj){
if (_.isUndefined(chain)) return;
if (_.isString(chain)) chain = chain.split('.');
// @TODO maybe lodash _.get?
return chain.reduce(function(result, link){
if (_.isPlainObject(result) || _.isArray(result)){
return result[link];
}
return undefined;
}, obj);
}
piConsoleFactory$1.$inject = ['$log'];
function piConsoleFactory$1($log){
return window.DEBUG ? piConsole : _.noop;
function piConsole(log){
if (_.get(piConsole,'settings.hideConsole', false)) return window.postMessage({type:'kill-console'},'*');
$log[log.type] && $log[log.type](log.message);
window.postMessage(noramlizeMessage(log),'*');
}
function noramlizeMessage(obj){
return _.cloneDeepWith(obj, normalize);
function normalize(val){
if (_.isFunction(val)) return val.toString();
if (_.isError(val)) return {name:val.name, message:val.message, stack:val.stack};
}
}
}
mixerRecursiveProvider.$inject = ['mixer'];
function mixerRecursiveProvider(mix){
function mixerRecursive(sequence, context, depth){
var mixed = [];
depth = depth || 0;
if (depth++ >= 10){
throw new Error('Mixer: the mixer allows a maximum depth of 10');
}
mixed = _(sequence)
.map(function(obj){
if (_.isUndefined(obj.mixer)){
return obj;
}
// mix object, and recursively mix the result
return mixerRecursive(mix(obj, context), context, depth);
})
.flatten()
.value();
return mixed;
}
return mixerRecursive;
}
var piConsole$1 = piConsoleFactory$1(console);
var mixer = mixProvider(
_.shuffle, // randomizeShuffle
Math.random // randomizeRandom
);
var mixerDotNotation = mixerDotNotationProvider$1(dotNotation$1);
var mixerCondition = mixerConditionProvider$1(
mixerDotNotation,
piConsole$1
);
var mixerEvaluate = evaluateProvider(mixerCondition);
var mixerDefaultContext = {};
var mixerRecursive = mixerRecursiveProvider(mixer);
mixerBranchingDecorator$1(
mixer,
mixerEvaluate,
mixerDefaultContext
);
var MixerSequence = mixerSequenceProvider$1(mixer);
templateObjProvider$1.$inject = ['templateDefaultContext'];
function templateObjProvider$1(templateDefaultContext){
function templateObj(obj, context, options){
var skip = _.get(options, 'skip', []);
var ctx = _.assign({}, context, templateDefaultContext);
return _.cloneDeepWith(obj, customizer);
function customizer(value, key, object){
if (obj === object && _.includes(skip, key)) return value;
if (_.isString(value) && _.includes(value, '<%')) return _.template(value)(ctx);
}
}
return templateObj;
}
var templateDefaultContext = {};
var templateObj = templateObjProvider$1(templateDefaultContext);
/*
* The constructor for an Array wrapper
*/
function collectionService(){
function Collection (arr) {
if (arr instanceof Collection) {
return arr;
}
// Make sure we are creating this array out of a valid argument
if (!_.isUndefined(arr) && !_.isArray(arr) && !(arr instanceof Collection)) {
throw new Error('Collections can only be constructed from arrays');
}
this.collection = arr || [];
this.length = this.collection.length;
// pointer to the current location within the array
// we start with -1 so that the initial next points to the begining of the array
this.pointer = -1;
}
_.extend(Collection.prototype,{
first : function first(){
this.pointer = 0;
return this.collection[this.pointer];
},
last : function last(){
this.pointer = this.collection.length - 1;
return this.collection[this.pointer];
},
end : function end(){
this.pointer = this.collection.length;
return undefined;
},
current : function(){
return this.collection[this.pointer];
},
next : function(){
return this.collection[++this.pointer];
},
previous : function(){
return this.collection[--this.pointer];
},
// add list of items to the collection
add : function(list){
// dont allow adding nothing
if (!arguments.length) {
return this;
}
// make sure list is as an array
list = _.isArray(list) ? list : [list];
this.collection = this.collection.concat(list);
this.length = this.collection.length;
return this;
},
// return the item at index
at: function(index){
return this.collection[index];
}
});
// Stuff we took out of bootstrap that can augment the collection
// **************************************************************
var methods = ['where','filter'];
var slice = Array.prototype.slice;
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.collection);
var coll = _.filter.apply(_,args);
return new Collection(coll);
};
});
return Collection;
}
// @TODO: repeat currently repeats only the last element, we need repeat = 'set' or something in order to prevent re-randomizing of exRandom...
RandomizerProvider.$inject = ['randomizeInt', 'randomizeRange', 'Collection'];
function RandomizerProvider(randomizeInt, randomizeRange, Collection){
function Randomizer(){
this._cache = {
random : {},
exRandom : {},
sequential : {}
};
}
_.extend(Randomizer.prototype, {
random: random,
exRandom: exRandom,
sequential: sequential
});
return Randomizer;
function random(length, seed, repeat){
var cache = this._cache.random;
if (repeat && !_.isUndefined(cache[seed])) {
return cache[seed];
}
// save result in cache
cache[seed] = randomizeInt(length);
return cache[seed];
}
function sequential(length, seed, repeat){
var cache = this._cache.sequential;
var coll = cache[seed];
var result;
// if needed create collection and set it in seed
if (_.isUndefined(coll)){
coll = cache[seed] = new Collection(_.range(length));
return coll.first();
}
if (coll.length !== length){
throw new Error('This seed ('+ seed +') points to a collection with the wrong length, you can only use a seed for sets of the same length');
}
// if this is a repeated element:
if (repeat) {
return coll.current();
}
// if we've reached the end
result = coll.next();
// if we've reached the end of the collection (next)
if (_.isUndefined(result)){
return coll.first();
} else {
return result;
}
}
function exRandom(length, seed, repeat){
var cache = this._cache.exRandom;
var coll = cache[seed];
var result;
// if needed create collection and set it in seed
if (_.isUndefined(coll)){
coll = cache[seed] = new Collection(randomizeRange(length));
return coll.first();
}
if (coll.length !== length){
throw new Error('This seed ('+ seed +') points to a collection with the wrong length, you can only use a seed for sets of the same length');
}
// if this is a repeated element:
if (repeat) {
return coll.current();
}
// if we've reached the end
result = coll.next();
// if we've reached the end of the collection (next)
// we should re-randomize
if (_.isUndefined(result)){
coll = cache[seed] = new Collection(randomizeRange(length));
return coll.first();
} else {
return result;
}
}
}
/*
* The store is a collection of collection devided into namespaces.
* You can think of every namespace/collection as a table.
*/
storeProvider$1.$inject = ['Collection'];
function storeProvider$1(Collection){
function Store(){
this.store = {};
}
_.extend(Store.prototype, {
create: function create(nameSpace){
if (this.store[nameSpace]){
throw new Error('The name space ' + nameSpace + ' already exists');
}
this.store[nameSpace] = new Collection();
this.store[nameSpace].namespace = nameSpace;
},
read: function read(nameSpace){
if (!this.store[nameSpace]){
throw new Error('The name space ' + nameSpace + ' does not exist');
}
return this.store[nameSpace];
},
update: function update(nameSpace, data){
var coll = this.read(nameSpace);
coll.add(data);
},
del: function del(nameSpace){
this.store[nameSpace] = undefined;
}
});
return Store;
}
SequenceProvider.$inject = ['MixerSequence'];
function SequenceProvider(MixerSequence){
/**
* Sequence Constructor:
* Manage the progression of a sequence, including parsing (mixing, inheritance and templating).
* @param {String } namespace [pages or questions (the type of db.Store)]
* @param {Array } arr [a sequence to manage]
* @param {Database} db [the db itself]
*/
function Sequence(namespace, arr,db){
this.namespace = namespace;
this.mixerSequence = new MixerSequence(arr);
this.db = db;
}
_.extend(Sequence.prototype, {
// only mix
next: function(context){
this.mixerSequence.next(context);
return this;
},
// anti mix
prev: function(context){
this.mixerSequence.prev(context);
return this;
},
/**
* Return the element currently in focus.
* It always returns either an element or undefined (mixers are abstrcted away)
* @param {[type]} context [description]
* @return {[type]} [description]
*/
current: function(context, options){
context || (context = {});
// must returned an element or undefined
var obj = this.mixerSequence.current(context);
// in case this is the end of the sequence
if (!obj){
return obj;
}
return this.db.inflate(this.namespace, obj, context, options);
},
/**
* Returns an array of elements, created by proceeding through the whole sequence.
* @return {[type]} [description]
*/
all: function(context, options){
var sequence = [];
var el = this.next().current(context, options);
while (el){
sequence.push(el);
el = this.next().current(context, options);
}
return sequence;
}
});
return Sequence;
}
DatabaseProvider.$inject = ['DatabaseStore', 'DatabaseRandomizer', 'databaseInflate', 'templateObj', 'databaseSequence','piConsole'];
function DatabaseProvider(Store, Randomizer, inflate, templateObj, DatabaseSequence, piConsole){
function Database(){
this.store = new Store();
this.randomizer = new Randomizer();
}
_.extend(Database.prototype, {
createColl: function(namespace){
this.store.create(namespace);
},
getColl: function(namespace){
return this.store.read(namespace);
},
add: function(namespace, query){
var coll = this.store.read(namespace);
coll.add(query);
},
inflate: function(namespace, query, context, options){
var coll = this.getColl(namespace);
var result;
// inherit
try {
if (!query.$inflated || query.reinflate) {
query.$inflated = inflate(query, coll, this.randomizer);
query.$templated = null; // we have to retemplate after querying, who know what new templates we got here...
}
} catch(err) {
piConsole({
type:'error',
message: 'Failed to inherit',
error:err,
context: query
});
if (this.onError) this.onError(err);
throw err;
}
// template
try {
if (!query.$templated || query.$inflated.regenerateTemplate){
context[namespace + 'Meta'] = query.$meta;
context[namespace + 'Data'] = templateObj(query.$inflated.data || {}, context, options); // make sure we support
query.$templated = templateObj(query.$inflated, context, options);
}
} catch(err) {
piConsole({
type:'error',
message: 'Failed to apply template',
error:err,
context: query.$inflated
});
if (this.onError) this.onError(err);
throw err;
}
result = query.$templated;
// set flags
if (context.global && result.addGlobal) _.extend(context.global, result.addGlobal);
if (context.current && result.addCurrent) _.extend(context.current, result.addCurrent);
return result;
},
sequence: function(namespace, arr){
if (!_.isArray(arr)){
throw new Error('Sequence must be an array.');
}
return new DatabaseSequence(namespace, arr, this);
}
});
return Database;
}
queryProvider$1.$inject = ['Collection'];
function queryProvider$1(Collection){
function queryFn(query, collection, randomizer){
var coll = new Collection(collection);
// shortcuts:
// ****************************
if (_.isFunction(query)) return query(collection);
if (_.isString(query) || _.isNumber(query)) query = {set:query, type:'random'};
// filter by set
// ****************************
if (query.set) coll = coll.filter({set:query.set});
// filter by data
// ****************************
if (_.isString(query.data)){
coll = coll.filter(function(q){
return q.handle === query.data || (q.data && q.data.handle === query.data);
});
}
if (_.isPlainObject(query.data)) coll = coll.filter({data:query.data});
if (_.isFunction(query.data)) coll = coll.filter(query.data);
// pick by type
// ****************************
// the default seed is namespace specific just to minimize the situations where seeds clash across namespaces
var seed = query.seed || ('$' + collection.namespace + query.set);
var length = coll.length;
var repeat = query.repeat;
var at;
switch (query.type){
case undefined:
case 'byData':
case 'random':
at = randomizer.random(length,seed,repeat);
break;
case 'exRandom':
at = randomizer.exRandom(length,seed,repeat);
break;
case 'sequential':
at = randomizer.sequential(length,seed,repeat);
break;
case 'first':
at = 0;
break;
case 'last':
at = length-1;
break;
default:
throw new Error('Unknow query type: ' + query.type);
}
if (_.isUndefined(coll.at(at))) throw new Error('Query failed, object (' + JSON.stringify(query) + ') not found. If you are trying to apply a template, you should know that they are not supported for inheritance.');
return coll.at(at);
}
return queryFn;
}
/*
* inflates an object
* this function is responsible for inheritance
*
* function inflate(source,coll, randomizer, recursive, counter)
* @param source: the object to inflate
* @param coll: a collection to inherit from
* @param randomizer: a randomizer object for the query
* @param recursive: private use only, is this inside the recursion (true) or top level (false)
* @param depth: private use only, a counter for the depth of the recursion
*/
inflateProvider$1.$inject = ['databaseQuery','$rootScope'];
function inflateProvider$1(query, $rootScope){
function customize(source){
// check for a custom function and run it if it exists
if (_.isFunction(source.customize)){
source.customize.apply(source, [source, $rootScope.global]);
}
return source;
}
// @param source - object to inflate
// @param type - trial stimulus or media
// @param recursive - whether this is a recursive call or not
function inflate(source, coll, randomizer, recursive, depth){
// protection against infinte loops
// ***********************************
depth = recursive ? --depth : 10;
if (!depth) throw new Error('Inheritance loop too deep, you can only inherit up to 10 levels down');
if (!_.isPlainObject(source)) throw new Error('You are trying to inflate a non object (' + JSON.stringify(source) + ')');