-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLW.js
870 lines (477 loc) · 20.2 KB
/
LW.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LW = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var LWdb = require('./LWdb');
function BoxOfQuestions(db) {
// private variables
var _question = null; // no current question
var _wordsToRepeat = null; // words which are eligible to be repeated.
// initialisation to null forces calculation
// on first call of wordsToRepeat()
var _status = {};
var _sessionExpiryTimeInSeconds = 1800;
// private methods
var _questionHasBeenProcessed = function(){
_question = null;
// This will trigger a new question, when LW.question()
// is called the next time.
};
var _updateSessionInfo = function(sessionExpiryTimeInSeconds){
// update session info in the _status object
// _status.sessionStartDateMS
// _status.sessionLastActivityDateMS
// _status.sessionIsNew
var dateTimeNow = (new Date()).valueOf(); // milliseconds
function createNewSession() {
_status.sessionStartDateMS = dateTimeNow;
_status.sessionLastActivityDateMS = _status.sessionStartDateMS;
_status.sessionStartDate = (new Date(dateTimeNow)).toJSON();
_status.sessionLastActivityDate = _status.sessionStartDate
_status.sessionIsNew = true;
}
function dateTimeDifferenceInSeconds(dateA, dateB) {
// calculate dateA - dateB
return (dateA - dateB)/ 1000
};
// if (sessionStartDateProperty does not exist)
if (!_status.hasOwnProperty("sessionStartDate")) {
// app has just started up. Thus we have no session yet.
createNewSession();
return _status
}
// check if session is expired ; 1800 seconds;
var previousActivityDate = _status.sessionLastActivityDateMS;
if (dateTimeDifferenceInSeconds(dateTimeNow,previousActivityDate) > sessionExpiryTimeInSeconds) {
createNewSession();
return _status
};
// we have an active session; just update sessionLastActivityDate
_status.sessionLastActivityDateMS = (new Date()).valueOf();
_status.sessionLastActivityDate = (new Date(_status.sessionLastActivityDateMS)).toJSON();
return _status
};
var _getRandomInt = function(min, max){
// Returns a random integer between min (inclusive) and max (inclusive)
// Using Math.round() will give you a non-uniform distribution!
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var _shuffle =function(a) {
var j, x, i;
for (i = a.length; i; i--) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
};
return a
};
// ===============================================================================
// literal object
// ===============================================================================
return {
version: '0.2.3beta',
db : db,
name : db.dbName,
chooseRandomObject : function(anArray){
return anArray[_getRandomInt(0,anArray.length-1)];
},
question : function(){
// gives back a question to ask
if (!_question) {
// _question is null, go for a new one.
var wds = this.wordsToRepeat();
if (wds != null) {_question = this.chooseRandomObject(wds)}
};
return _question
},
answer :function(){
var q = this.question();
// the answer text is either in a property 'translate' or 'answer'
if (q.translate) {return q.translate}
else {return q.answer}
// FIXME needs to be properly parameterized.
},
moveQuestionBackwards : function(){
if (_question) { // we have a question
// set new date for asking the question again;
// this has to be a a delay period later.
_question.date = new Date().valueOf() + (this.db.getSettings()).delay;
_question.step = 0;
this.db.putWord(_question);
// As the question has a new later date it is no more
// a current question
_questionHasBeenProcessed();
}
},
answerWasWrong : function(){this.moveQuestionBackwards()},
moveQuestionForward : function(){
if (_question) { // we have a question
var s = this.db.getSettings();
// calculate new date. This depends on which step the question is.
// And the delay calculation factor for that particular step.
_question.date = new Date().valueOf() +
s.delay * s.factorForDelayValue[_question.step];
// With repeated calls to this method
// the following will move the question up.
//
_question.step = _question.step + 1;
// The assumption is that long delay values for higher steps
// prevent an access error for
// s.factorForDelayValue[stepNumber]
this.db.putWord(_question);
// As the question has a new later date it is no more
// a current question
_questionHasBeenProcessed();
}
},
answerWasCorrect : function(){this.moveQuestionForward()},
importFrom : function(anArrayOfObjects){
this.db.importFrom(anArrayOfObjects);
},
getAnswerOptions : function(numberOfOptions){
// simple implementation : choose from all available words
// As we use ECMA5script findIndex is not available.
// We have to duplicate the effort in keeping an array of id
// numbers called idsOfOptions and an array of objects called
// options.
var n = (db.getSettings()).numberOfOptions;
var options = [];
if (db.numberOfWords() >= n) {
var q = this.question();
options.push(q);
var idsOfOptions = [];
idsOfOptions.push(q._id);
var anOption;
var allWords = this.db.allWords();
do {
// choose option from all words.
anOption = this.chooseRandomObject(allWords);
if (idsOfOptions.indexOf(anOption._id) == -1) {
// the new option is not included yet
idsOfOptions.push(anOption._id);
options.push(anOption)
}
} while (options.length < n);
};
return _shuffle(options)
},
config : function(config){
throw new Error("not yet implemented");
},
status : function(){
// give the number of words in the whole box,
// the number of words in the wordsToRepeat array and
// information about the session which was updated by _updateSessionInfo()
_status.numberOfWords = this.db.numberOfWords();
if (_wordsToRepeat) {_status.noOfWordsToRepeat = _wordsToRepeat.length};
return _status
},
addMoreWordsForLearning : function(n){
// update n words with step value < 0 to have a step value of 0
var lowestStepValue = this.db.getSettings().lowestStepValue;
var candidatesToAdd = this.wordsWithStepValue(lowestStepValue,-1);
// sort according to step value descending, e.g. -1,-2,-3 ...
// sort is in place
candidatesToAdd.sort(function(a,b) {return a.step < b.step});
var numberOfWordsToAdd;
// if not enough words are left to add only add what is available
if (n < candidatesToAdd.length) { numberOfWordsToAdd = n}
else {numberOfWordsToAdd = candidatesToAdd.length};
// Update db with new step values
for (var i = 0; i < numberOfWordsToAdd; i++){
(candidatesToAdd[i]).step = 0;
db.putWord(candidatesToAdd[i]);
}
},
wordsToRepeat : function(){
// calculate the array with words which are to be learned/repeated during a sessio
// all words with step value 0 and above are considered.
var lowestStep = 0;
// words with a date value >= todayNow are considered
var todayNow = new Date().valueOf();
// the function with the condition for inclusion into the result array
function isToBeRepeated(aWord) {
return (aWord.step >= lowestStep) && (todayNow >= aWord.date);
}
if (_question == null || _wordsToRepeat == null ) {
// _question == null means that either a question has never
// been asked before or that a question has been asked and
// processed but no new question yet has been picked.
// In both cases a new _wordsToRepeat collection is necessary.
_wordsToRepeat = (this.db.allWords()).filter(isToBeRepeated)
_sessionExpiryTimeInSeconds = (this.db.getSettings()).sessionExpiryTimeInSeconds;
_updateSessionInfo(_sessionExpiryTimeInSeconds);
if (_status.sessionIsNew) {
// the opportunity to check if we have enough _wordsToRepeat
var suggestedNumberOfWordsInASession = (this.db.getSettings()).suggestedNumberOfWordsInASession;
if (_wordsToRepeat.length < suggestedNumberOfWordsInASession) {
// we need to
this.addMoreWordsForLearning(suggestedNumberOfWordsInASession - _wordsToRepeat.length);
// and recalulate
_wordsToRepeat = (this.db.allWords()).filter(isToBeRepeated)
};
_status.sessionIsNew = false;
}
};
return _wordsToRepeat;
},
wordsWithStepValue : function(from, to){
var toValue;
if ( typeof(to) == "undefined" || to == null ) {toValue = from}
else {toValue = to}
function stepValueInRange(aWord) {
return (aWord.step >= from) && (aWord.step <= toValue);
}
return (this.db.allWords()).filter(stepValueInRange);
}
}
}
module.exports = BoxOfQuestions;
},{"./LWdb":2}],2:[function(require,module,exports){
(function (global){
"use strict";
// ----------------------------------------------------------------------
// LearnWords 2
//
// File:
// LWdb.js
//
// Purpose:
// Database layer
// Definition of an LWdb object
//
// Date:
// 10th January 2017
//
// ----------------------------------------------------------------------
if (typeof localStorage === "undefined" || localStorage === null) {
// we run in node thus we need to have a simulation of LocalStorage
var LocalStorage = require('node-localstorage').LocalStorage;
global.localStorage = new LocalStorage('./scratch');
}
var LWdb = function(name) {
// functional style,
// closure, returns an LWdb object
var dbName = name;
// private variables
var _keysOfAllWords = [];
var _numberOfWords = 0;
var recalculateIndex = true;
var _defaultInitialStepValue = -1;
// private methods
var _wdKeyFor = function(anInteger) {
return dbName+'-wd-'+anInteger;
};
var _setNumberOfWords = function(n) {
var key = dbName+'-numberOfWords';
localStorage.setItem(key,n);
_numberOfWords = n;
recalculateIndex = true;
};
var _incNumberOfWords = function() {
_setNumberOfWords(_numberOfWords + 1);
recalculateIndex = true;
};
var _invalidateIndex = function() {
recalculateIndex = true;
};
var _indexNeedsRecalculation = function() {
return recalculateIndex
};
var _indexHasBeenUpdated = function() {
recalculateIndex = false;
};
var _removeObjects = function(aKeyPrefix){
if (!!localStorage) { // this.isOK()
var key;
var st;
var keysToDelete = [];
// find all keys starting with aKeyPrefix
for (var i = 0; i < localStorage.length; i++){
key = localStorage.key(i);
st = localStorage.getItem(key);
if (key.lastIndexOf(aKeyPrefix,0) === 0) {
keysToDelete.push(key);
}
}
keysToDelete.forEach(function(aKey){
localStorage.removeItem(aKey);
});
}
};
// construct literal LWdb object
// methods and properties are public
return {
dbName : name,
putSettings : function(anObject) {
var key = dbName + '-settings';
return localStorage.setItem(key,JSON.stringify(anObject));
},
removeWords : function() {
var keys = this.keysOfAllWords();
for (var i = 0; i < keys.length; i++){
localStorage.removeItem(keys[i]);
}
_setNumberOfWords(0);
_invalidateIndex();
},
destroy : function() {
var aKeyPrefix = dbName;
_removeObjects(aKeyPrefix);
},
persistentStorageOK : function() {
return !!localStorage;
},
isOK : function() {
return this.persistentStorageOK();
},
numberOfWords : function() {
var key = dbName+'-numberOfWords';
var r = 0;
if (this.isOK()) {
r = localStorage.getItem(key);
if (r == null) {
localStorage.setItem(key,'0');
r = '0';
};
r = parseInt(r);
};
_numberOfWords = r;
return r;
},
putWord : function(aWord) {
if(!aWord._id){
throw "_id is required in a word";
}
if(!aWord.hasOwnProperty("step")){
aWord.step = _defaultInitialStepValue;
}
if(!aWord.date){
aWord.date = 0;
};
if (aWord.hasOwnProperty("answer")) {
// TODO use parametrization
var s = this.getSettings();
s.propertyAnswerText = "answer";
this.putSettings(s)
}
// get storage key
var storageKey = _wdKeyFor(aWord._id);
// try to get the word to check if it already exists
var value = localStorage.getItem(storageKey);
// save the word
localStorage.setItem(storageKey, JSON.stringify(aWord));
// if the word has not existed before increment the number of words
if (value == null) {
_incNumberOfWords();
};
// console.log('storageKey is=', storageKey, 'word is=', copy.word);
return storageKey;
},
getWord : function(anInteger) {
var storageKey = _wdKeyFor(anInteger);
try{
var aWord = JSON.parse(localStorage.getItem(storageKey));
if(!aWord.hasOwnProperty("step")){
aWord.step = _defaultInitialStepValue;
};
if(!aWord.date){
aWord.date = 0;
}
return aWord;
}catch(e){
return null;
}
},
importFrom : function(obj) {
var key;
var theWords;
if (typeof obj === "object") {
if (obj instanceof Array) {
theWords = obj
} else {
theWords = obj.words;
// TODO
// add import of settings
};
// import array of words
var n = theWords.length;
var aWord;
for(var i = 0; i < n; i++){
aWord = theWords[i];
key = this.putWord(aWord);
}
_invalidateIndex();
}
},
loadWords : function(theWords) {
this.importFrom(theWords);
},
keysOfAllWords : function() {
if (_indexNeedsRecalculation()) {
_keysOfAllWords = [];
var keyRegex = new RegExp("^"+dbName+"\\-wd\\-\\d+$");
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
// check it starts with <name>-wd-
if(keyRegex.test(key)){
_keysOfAllWords.push(key);
}
};
// _setNumberOfWords(_keysOfAllWords.length);
// as putWord() updates n
_indexHasBeenUpdated();
};
return _keysOfAllWords;
},
allWords : function() {
var keys = this.keysOfAllWords();
var words = [];
for(var i = 0; i < keys.length; i++){
var str = localStorage.getItem(keys[i]);
words.push(JSON.parse(str));
}
return words;
},
getSettings : function() {
var key = dbName + '-settings';
var value = localStorage.getItem(key);
// lazy initialisation
if (value==null) {
// define default value for settings
value = { "delay": 8640000,
"numberOfOptions": 4,
"factorForDelayValue": [1,1,3,7,45,90,360,1000],
"defaultInitialStepValue" : _defaultInitialStepValue,
"sessionExpiryTimeInSeconds" : 1800,
"suggestedNumberOfWordsInASession" : 20,
"lowestStepValue" : -10000,
"propertyAnswerText": "translate"
};
// One day = 24h * 60m * 60s * 1000 ms = 86'400'000 ms (milliseconds)
// the delay has been shortened to 1 day/10 for test purposes.
// this is 2h 24 min.
// the value is used to calculate the new date after a
// word has been answered correctly.
// "defaultInitialStepValue : -1 means that words means
// that words are available to be picked and sent to
// learn/repeat mode.
this.putSettings(value);
return value
} else {
return JSON.parse(value)
}
}
} // end of literal LWdb object
}; // end of LWdb function definition
module.exports = LWdb;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"node-localstorage":undefined}],3:[function(require,module,exports){
"use strict";
// Public LearnWords functions and properties that will be accessible in the
// LW namespace.
module.exports = {
BoxOfQuestions: require('./BoxOfQuestions'),
LWdb: require('./LWdb')
};
},{"./BoxOfQuestions":1,"./LWdb":2}]},{},[3])(3)
});