-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtng.js
741 lines (645 loc) · 22.8 KB
/
rtng.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
/**
*
* RTNG.js is a "Random Text and Number Generator"
* written by Michael Kubina
*
* https://github.com/michaelkubina/rtng-js
*
* 2023-02-08
*
*/
class rtng {
/**
*
*/
constructor() {
this.url;
this.promise;
this.externals;
}
/**
*
* @param {any} url
*/
async loadSchema(url) {
this.url = url;
let response = await fetch(url);
this.promise = await response.json();
}
/**
*
* @param {any} external
* @param {any} prepend_path
*/
adjustExternalTemplatePaths(external, prepend_path) {
let debug = false;
//console.log(">>> external");
//console.log(external);
var elements = Object.keys(external);
//console.log(elements);
for (const element of elements) {
if (typeof (external[element]) == "object" && element != "$sequence") {
//console.log(element + " is an object");
//console.log(">>> go deeper");
this.adjustExternalTemplatePaths(external[element], prepend_path);
}
else if (element == "$sequence") {
//console.log(element + " is a @sequence");
//console.log(external[element]);
for (let idx in external[element]) {
let primitive = Object.keys(external[element][idx]);
if (primitive == "template") {
//console.log(external[element][idx]['template']);
external[element][idx]['template'] = prepend_path + external[element][idx]['template'];
//console.log(external[element][idx]['template']);
}
}
}
}
}
/**
*
*/
async loadExternal() {
if (this.promise['@external'] != this.url) {
for (let idx in this.promise['@external']) {
let datapack = await rtng.init(this.promise['@external'][idx]);
let prepend_path = "@external." + idx + ".";
this.adjustExternalTemplatePaths(datapack['promise'], prepend_path);
this.promise['@external'][idx] = datapack['promise'];
}
}
}
/**
*
* @param {any} url
* @returns
*/
static async init(url) {
const object = new rtng();
await object.loadSchema(url);
await object.loadExternal();
return object;
}
/**
* Returns the value of the property at the given path. Depending on the path this coul be either string/number, array or an object.
* https://stackoverflow.com/questions/38640072/how-to-get-nested-objects-in-javascript-by-an-string-as-a-bracket-notation
* @param {path} path
*/
async getValue(path) {
let debug = false;
// start debug
if (debug) {
console.log(">>> getValue()");
console.log("path: " + path);
}
let value = path.replace(/\[([^\]]+)]/g, '.$1').split('.').reduce(function (o, p) {
return o[p];
}, await this.promise);
if (debug) {
console.log(value);
console.log("<<< getValue()");
}
return value;
}
/**
* Returns an array of full paths to all members at the current path
* @param {path} path - the path from where to list all members
*/
async listMembers(path = '') {
// return all members from datapack root
if (path === '') {
return Object.keys(await this.promise);
}
// get the value at the path
let value = await this.getValue(path);
// prevent to list string as indexed array
if (typeof value === 'string' || value instanceof String) {
return typeof value;
} else {
// get all keys from path
let allElements = Object.keys(value);
// add key to path in dot-notation
allElements.forEach((item, index) => allElements[index] = path + "." + item);
//console.log(allElements);
return allElements;
}
}
/**
* Returns an array only of those members of the current path with a @sequence as a child
* @param {path} path - the path from where to list all templates
*/
async listTemplates(path = '') {
let members = [];
let templates = [];
// gather all members
if (path === '') {
members = Object.keys(await this.promise);
} else {
members = Object.keys(await this.getValue(path));
path += '.';
}
// check wether a member has a @sequence
for (let idx in members) {
if (await this.getValue(path + members[idx] + '.@sequence') != undefined) {
templates.push(members[idx]);
}
}
return templates;
}
/**
* Returns an array only of those members of the current path that are
* objects and do not have a @sequence as a child
* @param {path} path - the path from where to list all categories
*/
async listCategories(path = '') {
let members = [];
let categories = [];
// gather all members
if (path === '') {
members = Object.keys(await this.promise);
} else {
members = Object.keys(await this.getValue(path));
path += '.';
}
// check wether a member is an object and does not have a @sequence
for (let i in members) {
if (await this.getValue(path + members[i] + '.@sequence') === undefined) {
let submembers = Object.keys(await this.getValue(path + members[i]));
let has_category = false;
for (let j in submembers) {
if (typeof await this.getValue(path + members[i] + '.' + submembers[j]) === 'object') {
has_category = true;
}
}
if (has_category) {
categories.push(path + members[i]);
}
}
}
return categories;
}
/**
* Returns an array only of those members of the current path that are
* strings or arrays and therefore metadata.
* @param {path} path - the path from where to list all categories
*/
async listMetadata(path = '') {
let members = [];
let metadata = [];
// gather all members
if (path === '') {
members = Object.keys(await this.promise);
} else {
members = Object.keys(await this.getValue(path));
path += '.';
}
// check wether a member is an object and does not have a @sequence
for (let i in members) {
let membertype = typeof await this.getValue(path + members[i]);
if (membertype === 'string') {
metadata.push(path + members[i]);
} else if (membertype === 'object') {
let membervalue = await this.getValue(path + members[i]);
if (Array.isArray(membervalue)) {
metadata.push(path + members[i]);
}
}
}
return metadata;
}
/**
* checks if element has specific name
* @param {any} path
* @param {any} name
*/
isElement(path, name) {
// check wether it is .title, .description, .anything etc.
if (path.endsWith('.' + name)) {
return true;
}
return false;
}
/**
* checks if element is object-element or a value/literal
* @param {any} path
*/
async isObject(path) {
let debug = false;
// check wether it is new hierarchy
if (typeof await this.getValue(path) === 'object' && Array.isArray(await this.getValue(path)) == false) {
console.log(path + " is object");
return true;
}
if (debug) console.log(path + " is NOT object");
return false;
}
/**
* checks if element has a sequence
* @param {any} path
*/
isSequence(path) {
return this.isElement(path, '@sequence');
}
/**
* checks if element has a external
* @param {any} path
*/
isExternal(path) {
return path.startsWith('@external');
}
/**
* add punctuation and conjunction to list
* @param {any} list
* @param {any} punctuation
* @param {any} conjunction
*/
applyPunctuation(list, punctuation, conjunction) {
// abort on empty list or list with only one item
if (list.length < 2) {
return list;
}
// add puncuation
if (punctuation) {
// add punctuation to all elements in array except the two last
for (let i = 0; i < list.length - 2; i++) {
list[i] = list[i] + punctuation;
}
if (conjunction) {
// add conjunction before the last
list.splice(list.length - 1, 0, conjunction);
} else {
// if there is no conjunction add punctuation instead
list[list.length - 2] = list[list.length - 2] + punctuation;
}
return list;
}
}
/**
* Returns a sorted list of values (lexicographically or numerical)
* @param {any} list
* @param {any} sort
*/
applySort(list, sort) {
// abort on empty list or list with only one item and when no sorting direction
if (list.length < 2 || sort == "none") {
return list;
}
// sort string lexicographically and numbers numerically
if (typeof(list[0]) == "number" && sort == "asc") {
return list.sort(function (a, b) { return a - b });
}
if (typeof (list[0]) == "number" && sort == "desc") {
return list.sort(function (a, b) { return b - a });
}
if (typeof (list[0]) == "string" && sort == "asc") {
return list.sort();
}
if (typeof (list[0]) == "string" && sort == "desc") {
return list.sort().reverse();
}
}
/**
*
* @param {any} min_picks
* @param {any} max_picks
* @param {any} min
* @param {any} max
* @param {any} steps
* @param {any} unique
* @returns
*/
getPicks(min_picks, max_picks, min, max, steps, unique) {
let debug = false;
if (debug) {
console.log(">>> getPicks()");
console.log("min_picks: " + min_picks);
console.log("max_picks: " + max_picks);
console.log("min: " + min);
console.log("max: " + max);
console.log("steps: " + steps);
console.log("unique: " + unique);
}
let result = [];
// a number between min_picks (inclusive) and max_picks (inclusive)
let picks = Math.floor(Math.random() * (max_picks - min_picks + 1) + min_picks);
if (debug) console.log("> picks: " + picks);
// abort on no picks
if (!picks) {
if (debug) console.log("<<< getPicks()");
return result = [''];
}
// random pick (unique or repeatable)
for (let i = 1; i <= picks; i++) {
// add random list item
let random_number;
if (unique) {
let unique_pick = false;
while (!unique_pick) { // TIMEOUT ENDLESS LOOP BUG???
random_number = Math.round(Math.random() * ((max - min) / steps)); // random pick
random_number = random_number * steps + min;
if (debug) console.log(random_number);
if (result.includes(random_number)) {
unique_pick = false; // not necessary
} else {
result.push(random_number);
unique_pick = true;
}
}
} else {
random_number = Math.round(Math.random() * ((max - min) / steps)); // random pick
random_number = random_number * steps + min;
result.push(random_number);
}
}
if (debug) console.log("<<< getPicks()");
return result;
}
/**
*
* @param {any} output
* @param {any} sort
* @param {any} punctuation
* @param {any} conjunction
* @returns
*/
processOutput(output, sort, punctuation, conjunction) {
let debug = false;
// start debug
if (debug) console.log(">>> processOutput()");
// sort
if (sort != "none") {
output = this.applySort(output, sort);
if (debug) {
console.log("> sort >");
console.log(output);
}
}
// punctuate
if (punctuation || conjunction) {
output = this.applyPunctuation(output, punctuation, conjunction);
if (debug) {
console.log("> punctuate >");
console.log(output);
}
}
// join
output = output.join(' ');
if (debug) {
console.log("> join >");
console.log(output);
}
// start debug
if (debug) console.log("<<< processOutput()");
return output
}
/**
* return a parameter object preseeded with defaults where necessary
* @param {any} object
* @returns
*/
async loadParameters(object) {
let debug = false;
// defaults
let params = {
// picking
min_picks: 1,
max_picks: 1,
unique: true,
// processing
sort: "none",
punctuation: '',
conjunction: '',
}
// optional
if (object != undefined) {
if (await object.min_picks >= 0) params.min_picks = await object.min_picks;
if (await object.max_picks >= 0) params.max_picks = await object.max_picks;
if (typeof (await object.unique) == "boolean") params.unique = await object.unique;
if (await object.sort) params.sort = await object.sort;
if (await object.punctuation) params.punctuation = await object.punctuation;
if (await object.conjunction) params.conjunction = await object.conjunction;
}
// debug parameters
if (debug) {
console.log("min_picks: " + params.min_picks);
console.log("max_picks: " + params.max_picks);
console.log("unique: " + params.unique);
console.log("sort: " + params.sort);
console.log("punctuation: " + params.punctuation);
console.log("conjunction: " + params.conjunction);
}
return params;
}
/**
*
* @param {any} object
* @returns
*/
async parseString(object) {
let debug = false;
// start debug
if (debug) console.log(">>> BEGIN PARSING STRING");
if (debug) console.log(object);
// output
let output = [];
let params = await this.loadParameters(object.params);
// if single value, return directly
if (typeof object.string === 'string') {
// end debug
if (debug) console.log("<<< END PARSING STRING");
return object.string;
}
// if just an array and nothing more
if (Object.keys(object).length == 1) {
// pick just one
let idx = this.getPicks(1, 1, 0, object.string.length - 1, 1, true);
// end debug
if (debug) console.log("<<< END PARSING STRING");
return object.string[idx];
}
// required
let number_of_items = await object.string.length;
// pick
let picks = this.getPicks(params.min_picks, params.max_picks, 0, number_of_items - 1, 1, params.unique);
if (debug) {
console.log("> picks (index) >");
console.log(picks);
}
for (let i in picks) {
output.push(object.string[picks[i]]);
}
if (debug) {
console.log("> picks (value) >");
console.log(output);
}
// process output
output = this.processOutput(output, params.sort, params.punctuation, params.conjunction);
// end debug
if (debug) console.log("<<< END PARSING STRING");
return output;
}
/**
* parse a number object within a sequence
* @param {any} object
*/
async parseNumber(object) {
let debug = false;
// start debug
if (debug) console.log(">>> BEGIN PARSING NUMBER");
// output
let output = [];
// defaults
let min;
let max;
let steps = 1;
let params = await this.loadParameters(object.params);
// if single value, return directly
if (typeof object.number === 'number') {
// end debug
if (debug) console.log("<<< END PARSING NUMBER");
return object.number;
}
// if just an array and nothing more
if (Object.keys(object).length == 1 && object.number instanceof Array) {
// pick just one
let idx = this.getPicks(1, 1, 0, object.number.length - 1, 1, true);
// end debug
if (debug) console.log("<<< END PARSING NUMBER");
return object.number[idx];
}
// get required
if (await object.number.min) min = await object.number.min;
if (await object.number.max) max = await object.number.max;
// get optional
if (await object.number.steps > 0) steps = await object.number.steps;
// debug parameters
if (debug) {
console.log("min: " + min);
console.log("max: " + max);
console.log("steps: " + steps);
}
// if an array and additional parameters
if (Object.keys(object).length > 1 && object.number instanceof Array) {
// pick
let picks = this.getPicks(params.min_picks, params.max_picks, 0, object.number.length - 1, 1, params.unique);
if (debug) {
console.log("> picks (index) >");
console.log(picks);
}
for (let i in picks) {
output.push(object.number[picks[i]]);
}
if (debug) {
console.log("> picks (value) >");
console.log(output);
}
} else {
// if pick via parameters
output = this.getPicks(params.min_picks, params.max_picks, min, max, params.steps, params.unique);
if (debug) {
console.log("> pick >");
console.log(output);
}
}
// process output
if (params.punctuation || params.conjunction) {
output = this.processOutput(output, params.sort, params.punctuation, params.conjunction);
}
// end debug
if (debug) console.log("<<< END PARSING NUMBER");
return output;
}
/**
* parse a template object
* @param {any} path
*/
async parseTemplate(path) {
// debug flag
let debug = false;
// start debugging
if (debug) console.log('>>> parseTemplate(' + path + ')');
// return object
let output = [];
// get the sequence objects at the path
let sequence = await this.getValue(path + '.@sequence');
if (debug) console.log('> sequence');
if (debug) console.log(sequence);
// abort if no sequence objects and thus not a template
if (sequence === undefined) {
if (debug) console.log('<<< parseTemplate(' + path + ')');
return 'ERROR - "' + path + '" is not a template';
}
// go through the list of objects
for await (const sequence_object of sequence) {
if (debug) console.log('> sequence_object');
if (debug) console.log(sequence_object);
if ('string' in sequence_object) {
output.push(await this.parseString(sequence_object));
}
else if ('number' in sequence_object) {
output.push(await this.parseNumber(sequence_object));
}
else if ('template' in sequence_object) {
let params = await this.loadParameters(sequence_object.params);
if (debug) console.log(params);
// TODO: make sure not to fall into infinite loop!!!???
// if single value, return directly
if (typeof sequence_object.template === 'string') {
// end debug
if (debug) console.log('> end parsing @sequence');
output.push(await this.parseTemplate(sequence_object.template));
}
// if just an array and nothing more
if (Object.keys(sequence_object).length == 1) {
// pick just one
let idx = this.getPicks(1, 1, 0, sequence_object.template.length - 1, 1, true);
// end debug
if (debug) console.log('> end parsing @sequence');
output.push(await this.parseTemplate(sequence_object.template[idx]));
}
// required
let number_of_items = await sequence_object.template.length;
// pick
let picks = this.getPicks(params.min_picks, params.max_picks, 0, number_of_items - 1, 1, params.unique);
if (debug) {
console.log("> picks (index) >");
console.log(picks);
}
for (let i in picks) {
output.push(await this.parseTemplate(sequence_object.template[picks[i]]));
}
if (debug) {
console.log("> picks (value) >");
console.log(output);
}
// process output
output = this.processOutput(output, params.sort, params.punctuation, params.conjunction);
}
}
if (debug) console.log('> end parsing @sequence');
if (output instanceof Array) {
if (output.length > 1) return output.join(' ');
else return output[0];
} else {
return output;
}
}
/**
* checks if a element is a template (= has a @sequence)
* @param {any} path
*/
async isTemplate(path) {
// get a list of paths of all sub-elements for a given path
let elements = await this.listMembers(path);
// if it's actually a list
if (Array.isArray(await elements)) {
// look if it has a @sequenceitem
for await (const item of elements)
if (item.endsWith('.@sequence')) {
return true;
}
}
return false;
}
}