This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjspsych.js
1586 lines (1311 loc) · 41.7 KB
/
jspsych.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
/**
* jspsych.js
* Josh de Leeuw
*
* documentation: docs.jspsych.org
*
**/
var jsPsych = (function() {
var core = {};
//
// private variables
//
// options
var opts = {};
// experiment timeline
var timeline;
// flow control
var global_trial_index = 0;
var current_trial = {};
// target DOM element
var DOM_target;
// time that the experiment began
var exp_start_time;
//
// public methods
//
core.init = function(options) {
// reset variables
timeline = null;
global_trial_index = 0;
current_trial = {};
// check if there is a #experiment-container on the page
var default_display_element = $('.experiment-container');
if (default_display_element.length === 0) {
$(document.documentElement).append($('<div class="experiment-container">'));
default_display_element = $('#experiment-container');
}
var defaults = {
'display_element': default_display_element,
'on_finish': function(data) {
return undefined;
},
'on_trial_start': function() {
return undefined;
},
'on_trial_finish': function() {
return undefined;
},
'on_data_update': function(data) {
return undefined;
},
'show_progress_bar': false,
'auto_preload': true,
'max_load_time': 30000,
'skip_load_check': false,
'fullscreen': false,
'default_iti': 1000
};
// override default options if user specifies an option
opts = $.extend({}, defaults, options);
// set target
DOM_target = opts.display_element;
// add CSS class to DOM_target
DOM_target.addClass('jspsych-display-element');
// create experiment timeline
timeline = new TimelineNode({
timeline: opts.timeline
});
// preloading
if(opts.auto_preload){
jsPsych.pluginAPI.autoPreload(timeline, startExperiment);
} else {
startExperiment();
}
};
core.progress = function() {
var percent_complete = timeline.percentComplete()
var obj = {
"total_trials": timeline.length(),
"current_trial_global": global_trial_index,
"percent_complete": percent_complete
};
return obj;
};
core.startTime = function() {
return exp_start_time;
};
core.totalTime = function() {
return (new Date()).getTime() - exp_start_time.getTime();
};
core.getDisplayElement = function() {
return DOM_target;
};
core.finishTrial = function(data) {
// write the data from the trial
data = typeof data == 'undefined' ? {} : data;
jsPsych.data.write(data);
// get back the data with all of the defaults in
var trial_data = jsPsych.data.getDataByTrialIndex(global_trial_index);
// handle callback at plugin level
if (typeof current_trial.on_finish === 'function') {
current_trial.on_finish(trial_data);
}
// handle callback at whole-experiment level
opts.on_trial_finish(trial_data);
// wait for iti
if (typeof current_trial.timing_post_trial == 'undefined') {
if (opts.default_iti > 0) {
setTimeout(next_trial, opts.default_iti);
} else {
next_trial();
}
} else {
if (current_trial.timing_post_trial > 0) {
setTimeout(next_trial, current_trial.timing_post_trial);
} else {
next_trial();
}
}
function next_trial() {
global_trial_index++;
// advance timeline
var complete = timeline.advance();
// update progress bar if shown
if (opts.show_progress_bar === true) {
updateProgressBar();
}
// check if experiment is over
if (complete) {
finishExperiment();
return;
}
doTrial(timeline.trial());
}
};
core.endExperiment = function(end_message) {
timeline.end_message = end_message;
timeline.end();
}
core.endCurrentTimeline = function() {
timeline.endActiveNode();
}
core.currentTrial = function() {
return current_trial;
};
core.initSettings = function() {
return opts;
};
core.currentTimelineNodeID = function() {
return timeline.activeID();
};
function TimelineNode(parameters, parent, relativeID) {
// a unique ID for this node, relative to the parent
var relative_id;
// store the timeline for this node
var timeline = [];
// store the parent for this node
var parent_node;
// if there is a loop function, store it
var loop_function;
// if there is a conditional function, store it
var conditional_function;
// data for the trial if this node is a trial
var trial_data;
// flag to randomize the order of the trials
var randomize_order = false;
// keep track of progress
var current_location = 0;
var current_iteration = 0;
// flag to force the node to be finished
var done_flag = false;
// reference to self
var self = this;
// constructor
var _construct = function() {
// store a link to the parent of this node
parent_node = parent;
// create the ID for this node
if (typeof parent == 'undefined') {
relative_id = 0;
}
relative_id = relativeID;
// check if there is a timeline parameter
// if there is, then this is not a trial node
if (typeof parameters.timeline !== 'undefined') {
// extract all of the node level data and parameters
var node_data = $.extend(true, {}, parameters);
delete node_data.timeline;
delete node_data.conditional_function;
delete node_data.loop_function;
delete node_data.randomize_order;
// create a TimelineNode for each element in the timeline
for (var i = 0; i < parameters.timeline.length; i++) {
timeline.push(new TimelineNode($.extend(true, {}, node_data, parameters.timeline[i]), self, i));
}
// store the loop function if it exists
if (typeof parameters.loop_function !== 'undefined') {
loop_function = parameters.loop_function;
}
// store the conditional function if it exists
if (typeof parameters.conditional_function !== 'undefined') {
conditional_function = parameters.conditional_function;
}
// flag to randomize the order of trials
if (typeof parameters.randomize_order !== 'undefined') {
randomize_order = parameters.randomize_order;
}
if (randomize_order === true) {
timeline = jsPsych.randomization.shuffle(timeline);
}
}
// if there is no timeline parameter, then this node is a trial node
else {
// check to see if a valid trial type is defined
var trial_type = parameters.type;
if (typeof trial_type == 'undefined') {
console.error('Trial level node is missing the "type" parameter. The parameters for the node are: ' + JSON.stringify(parameters));
} else if (typeof jsPsych.plugins[trial_type] == 'undefined') {
console.error('No plugin loaded for trials of type "' + trial_type + '"');
}
// create a deep copy of the parameters for the trial
trial_data = $.extend(true, {}, parameters);
}
}();
// recursively get the number of **trials** contained in the timeline
// assuming that while loops execute exactly once and if conditionals
// always run
this.length = function() {
var length = 0;
if (timeline.length > 0) {
for (var i = 0; i < timeline.length; i++) {
length += timeline[i].length();
}
} else {
return 1;
}
return length;
}
// recursively get the next trial to run.
// if this node is a leaf (trial), then return the trial.
// otherwise, recursively find the next trial in the child timeline.
this.trial = function() {
if (timeline.length == 0) {
return trial_data;
} else {
if (current_location >= timeline.length) {
return null;
} else {
return timeline[current_location].trial();
}
}
}
// update the current trial node to be completed
// returns true if the node is complete after advance
// returns false otherwise
this.advance = function() {
// first check to see if this node is done
if(done_flag){
return true;
}
// propogate down to the current trial, and update the current_location
// of that node (effectively ending that node)
if (timeline.length !== 0) {
if (timeline[current_location].advance()) {
// if this returns true, then the node below is complete, and we need to
// advance this node.
current_location++;
if (this.checkCompletion()) {
return true;
} else {
// we advanced the node, now we need to check if the node we advanced
// to is also complete, and keep advancing until we find a node that
// is not complete, or until this node is complete.
while (!this.checkCompletion() && timeline[current_location].checkCompletion()) {
current_location++;
}
if (this.checkCompletion()) {
return true;
} else {
return false;
}
}
} else {
// if this returns false, then the node below is not complete, and we
// don't need to do anything else here
return false;
}
} else {
// if we get here, then this is a trial node, and the node is complete
current_location++;
done_flag = true;
return true;
}
}
// return true if the node is completely done (no more possible trials)
// otherwise, return false
this.checkCompletion = function() {
// if the done_flag is true, the node is complete no matter what.
if (done_flag) {
return true;
}
// check for trial nodes
if (timeline.length == 0 && current_location > 0) {
done_flag = true;
return true;
}
// check for non-trial nodes
if (timeline.length > 0) {
// checking nodes that have reached the end of the timeline.
// if there is a loop function, evaluate it.
// otherwise, the node is done.
if (current_location >= timeline.length) {
// check if there is a loop function
if (typeof loop_function !== 'undefined') {
if (loop_function(this.generatedData())) {
this.reset();
} else {
done_flag = true;
return true;
}
} else {
done_flag = true;
return true;
}
}
// checking nodes with conditional functions
if (typeof conditional_function !== 'undefined' && current_location == 0) {
if (conditional_function()) {
// run the timeline
return false;
} else {
// skip the timeline
done_flag = true;
return true;
}
}
}
return false;
}
// check the status of the done flag
this.isComplete = function() {
return done_flag;
}
// return the percentage of trials completed, grouped at the first child level
// counts a set of trials as complete when the child node is done
this.percentComplete = function() {
var total_trials = this.length();
var completed_trials = 0;
for (var i = 0; i < timeline.length; i++) {
if (timeline[i].isComplete()) {
completed_trials += timeline[i].length();
}
}
return (completed_trials / total_trials * 100)
}
// reset the location pointer to the start of the timeline, and reset all the
// child nodes on the timeline.
this.reset = function() {
current_location = 0;
done_flag = false;
if (timeline.length > 0) {
for (var i = 0; i < timeline.length; i++) {
timeline[i].reset();
}
if (randomize_order === true) {
timeline = jsPsych.randomization.shuffle(timeline);
}
} else {
// reset the parameters of this trial to the original parameters, which
// will reset any functions-as-parameters to the function.
trial_data = $.extend(true, {}, parameters);
}
current_iteration++;
}
// mark this node as finished
this.end = function() {
done_flag = true;
}
// recursively end whatever sub-node is running the current trial
this.endActiveNode = function() {
if (timeline.length == 0) {
this.end();
parent_node.end();
} else {
timeline[current_location].endActiveNode();
}
}
// get a unique ID associated with this node
// the ID reflects the current iteration through this node.
this.ID = function() {
var id = "";
if (typeof parent_node == 'undefined') {
return "0." + current_iteration;
} else {
id += parent_node.ID() + "-";
id += relative_id + "." + current_iteration;
return id;
}
}
// get the ID of the active trial
this.activeID = function() {
if (timeline.length == 0) {
return this.ID();
} else {
return timeline[current_location].activeID();
}
}
// get all the data generated within this node
this.generatedData = function() {
return jsPsych.data.getDataByTimelineNode(this.ID());
}
// get all the trials of a particular type
this.trialsOfType = function(type) {
if (timeline.length == 0) {
if (trial_data.type == type) {
return trial_data;
} else {
return [];
}
} else {
var trials = [];
for (var i = 0; i < timeline.length; i++) {
var t = timeline[i].trialsOfType(type);
trials = trials.concat(t);
}
return trials;
}
}
}
function startExperiment() {
var fullscreen = opts.fullscreen;
// fullscreen setup
if (fullscreen) {
// check if keys are allowed in fullscreen mode
var keyboardNotAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
if (keyboardNotAllowed) {
go();
} else {
DOM_target.append('<div><p>The experiment will launch in fullscreen mode when you click the button below.</p><button id="jspsych-fullscreen-btn" class="md-button md-raised md-primary">Launch Experiment</button></div>');
$('#jspsych-fullscreen-btn').on('click', function() {
var element = document.documentElement;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
$('#jspsych-fullscreen-btn').off('click');
DOM_target.html('');
go();
});
}
} else {
go();
}
function go() {
// show progress bar if requested
if (opts.show_progress_bar === true) {
drawProgressBar();
}
// record the start time
exp_start_time = new Date();
// begin!
doTrial(timeline.trial());
}
}
function finishExperiment() {
opts.on_finish(jsPsych.data.getData());
if(typeof timeline.end_message !== 'undefined'){
DOM_target.html(timeline.end_message);
}
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
function doTrial(trial) {
current_trial = trial;
// call experiment wide callback
opts.on_trial_start();
// check if trial has it's own display element
var display_element = DOM_target;
if(typeof trial.display_element !== 'undefined'){
display_element = trial.display_element;
}
// execute trial method
jsPsych.plugins[trial.type].trial(display_element, trial);
}
function drawProgressBar() {
$('#jspsych-container').prepend($('<div id="jspsych-progressbar-container"><span>Completion Progress</span><md-progress-linear md-mode="determinate" value="0"></md-progress-linear></div>'));
}
function updateProgressBar() {
var progress = jsPsych.progress();
$('#jspsych-progressbar-inner').attr('value', progress.percent_complete);
}
return core;
})();
jsPsych.plugins = {};
jsPsych.data = (function() {
var module = {};
// data storage object
var allData = [];
// data properties for all trials
var dataProperties = {};
module.getData = function() {
return $.extend(true, [], allData); // deep clone
};
module.write = function(data_object) {
var progress = jsPsych.progress();
var trial = jsPsych.currentTrial();
//var trial_opt_data = typeof trial.data == 'function' ? trial.data() : trial.data;
var default_data = {
'trial_type': trial.type,
'trial_index': progress.current_trial_global,
'time_elapsed': jsPsych.totalTime(),
'internal_node_id': jsPsych.currentTimelineNodeID()
};
var ext_data_object = $.extend({}, data_object, trial.data, default_data, dataProperties);
allData.push(ext_data_object);
var initSettings = jsPsych.initSettings();
initSettings.on_data_update(ext_data_object);
};
module.addProperties = function(properties) {
// first, add the properties to all data that's already stored
for (var i = 0; i < allData.length; i++) {
for (var key in properties) {
allData[i][key] = properties[key];
}
}
// now add to list so that it gets appended to all future data
dataProperties = $.extend({}, dataProperties, properties);
};
module.addDataToLastTrial = function(data) {
if (allData.length == 0) {
throw new Error("Cannot add data to last trial - no data recorded so far");
}
allData[allData.length - 1] = $.extend({}, allData[allData.length - 1], data);
}
module.dataAsCSV = function() {
var dataObj = module.getData();
return JSON2CSV(dataObj);
};
module.dataAsJSON = function() {
var dataObj = module.getData();
return JSON.stringify(dataObj);
};
module.localSave = function(filename, format) {
var data_string;
if (format == 'JSON' || format == 'json') {
data_string = JSON.stringify(module.getData());
} else if (format == 'CSV' || format == 'csv') {
data_string = module.dataAsCSV();
} else {
throw new Error('invalid format specified for jsPsych.data.localSave');
}
saveTextToFile(data_string, filename);
};
module.getTrialsOfType = function(trial_type) {
var data = module.getData();
data = flatten(data);
var trials = [];
for (var i = 0; i < data.length; i++) {
if (data[i].trial_type == trial_type) {
trials.push(data[i]);
}
}
return trials;
};
module.getDataByTimelineNode = function(node_id) {
var data = module.getData();
data = flatten(data);
var trials = [];
for (var i = 0; i < data.length; i++) {
if (data[i].internal_node_id.slice(0, node_id.length) === node_id) {
trials.push(data[i]);
}
}
return trials;
};
module.getLastTrialData = function() {
if (allData.length == 0) {
return {};
}
return allData[allData.length - 1];
};
module.getDataByTrialIndex = function(trial_index) {
for (var i = 0; i < allData.length; i++) {
if (allData[i].trial_index == trial_index) {
return allData[i];
}
}
return undefined;
}
module.getLastTimelineData = function() {
var lasttrial = module.getLastTrialData();
var node_id = lasttrial.internal_node_id;
if (typeof node_id === 'undefined') {
return [];
} else {
var parent_node_id = node_id.substr(0,node_id.lastIndexOf('-'));
var lastnodedata = module.getDataByTimelineNode(parent_node_id);
return lastnodedata;
}
}
module.displayData = function(format) {
format = (typeof format === 'undefined') ? "json" : format.toLowerCase();
if (format != "json" && format != "csv") {
console.log('Invalid format declared for displayData function. Using json as default.');
format = "json";
}
var data_string;
if (format == 'json') {
data_string = JSON.stringify(module.getData(), undefined, 1);
} else {
data_string = module.dataAsCSV();
}
var display_element = jsPsych.getDisplayElement();
display_element.append($('<pre id="jspsych-data-display"></pre>'));
$('#jspsych-data-display').text(data_string);
};
module.urlVariables = function() {
return query_string;
}
module.getURLVariable = function(whichvar){
return query_string[whichvar];
}
// private function to save text file on local drive
function saveTextToFile(textstr, filename) {
var blobToSave = new Blob([textstr], {
type: 'text/plain'
});
var blobURL = "";
if (typeof window.webkitURL !== 'undefined') {
blobURL = window.webkitURL.createObjectURL(blobToSave);
} else {
blobURL = window.URL.createObjectURL(blobToSave);
}
var display_element = jsPsych.getDisplayElement();
display_element.append($('<a>', {
id: 'jspsych-download-as-text-link',
href: blobURL,
css: {
display: 'none'
},
download: filename,
html: 'download file'
}));
$('#jspsych-download-as-text-link')[0].click();
}
//
// A few helper functions to handle data format conversion
//
// this function based on code suggested by StackOverflow users:
// http://stackoverflow.com/users/64741/zachary
// http://stackoverflow.com/users/317/joseph-sturtevant
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var line = '';
var result = '';
var columns = [];
var i = 0;
for (var j = 0; j < array.length; j++) {
for (var key in array[j]) {
var keyString = key + "";
keyString = '"' + keyString.replace(/"/g, '""') + '",';
if ($.inArray(key, columns) == -1) {
columns[i] = key;
line += keyString;
i++;
}
}
}
line = line.slice(0, -1);
result += line + '\r\n';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var j = 0; j < columns.length; j++) {
var value = (typeof array[i][columns[j]] === 'undefined') ? '' : array[i][columns[j]];
var valueString = value + "";
line += '"' + valueString.replace(/"/g, '""') + '",';
}
line = line.slice(0, -1);
result += line + '\r\n';
}
return result;
}
// this function is from StackOverflow:
// http://stackoverflow.com/posts/3855394
var query_string = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
return module;
})();
jsPsych.turk = (function() {
var module = {};
// core.turkInfo gets information relevant to mechanical turk experiments. returns an object
// containing the workerID, assignmentID, and hitID, and whether or not the HIT is in
// preview mode, meaning that they haven't accepted the HIT yet.
module.turkInfo = function() {
var turk = {};
var param = function(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
return (results == null) ? "" : results[1];
};
var src = param(window.location.href, "assignmentId") ? window.location.href : document.referrer;
var keys = ["assignmentId", "hitId", "workerId", "turkSubmitTo"];
keys.map(
function(key) {
turk[key] = unescape(param(src, key));
});
turk.previewMode = (turk.assignmentId == "ASSIGNMENT_ID_NOT_AVAILABLE");
turk.outsideTurk = (!turk.previewMode && turk.hitId === "" && turk.assignmentId == "" && turk.workerId == "")
turk_info = turk;
return turk;
};
// core.submitToTurk will submit a MechanicalTurk ExternalHIT type
module.submitToTurk = function(data) {
var turkInfo = jsPsych.turk.turkInfo();
var assignmentId = turkInfo.assignmentId;
var turkSubmitTo = turkInfo.turkSubmitTo;
if (!assignmentId || !turkSubmitTo) return;
var dataString = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
dataString.push(key + "=" + escape(data[key]));
}
}
dataString.push("assignmentId=" + assignmentId);
var url = turkSubmitTo + "/mturk/externalSubmit?" + dataString.join("&");
window.location.href = url;
};
return module;
})();
jsPsych.randomization = (function() {
var module = {};
module.repeat = function(array, repetitions, unpack) {
var arr_isArray = Array.isArray(array);
var rep_isArray = Array.isArray(repetitions);
// if array is not an array, then we just repeat the item
if (!arr_isArray) {
if (!rep_isArray) {
array = [array];
repetitions = [repetitions];
} else {
repetitions = [repetitions[0]];
console.log('Unclear parameters given to randomization.repeat. Multiple set sizes specified, but only one item exists to sample. Proceeding using the first set size.');
}
} else {
if (!rep_isArray) {
var reps = [];
for (var i = 0; i < array.length; i++) {
reps.push(repetitions);
}
repetitions = reps;
} else {
if (array.length != repetitions.length) {
console.warning('Unclear parameters given to randomization.repeat. Items and repetitions are unequal lengths. Behavior may not be as expected.');
// throw warning if repetitions is too short, use first rep ONLY.
if (repetitions.length < array.length) {
var reps = [];
for (var i = 0; i < array.length; i++) {
reps.push(repetitions);
}
repetitions = reps;
} else {
// throw warning if too long, and then use the first N
repetitions = repetions.slice(0, array.length);
}
}
}
}
// should be clear at this point to assume that array and repetitions are arrays with == length
var allsamples = [];
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < repetitions[i]; j++) {
allsamples.push(array[i]);
}
}
var out = shuffle(allsamples);
if (unpack) {
out = unpackArray(out);
}
return out;
}
module.shuffle = function(arr) {
return shuffle(arr);
}
module.shuffleNoRepeats = function(arr, equalityTest) {
// define a default equalityTest
if (typeof equalityTest == 'undefined') {
equalityTest = function(a, b) {
if (a === b) {
return true;
} else {
return false;
}
}
}
var random_shuffle = shuffle(arr);
for (var i = 0; i < random_shuffle.length - 2; i++) {