-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpickUnique.js
96 lines (77 loc) · 2.16 KB
/
pickUnique.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
(function pickUniqueUtil() {
'use strict';
/* globals random, Story */
const lastIndex = '__lastIndex';
function has(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function _extendArray(arr, value = null) {
if (!Array.isArray(arr)) {
throw new TypeError('Not an array');
}
if (value === null) {
value = random(arr.length - 1);
}
Object.defineProperty(arr, lastIndex, {
enumerable: false,
writable: true,
value,
});
}
function _getNextUnique(arr) {
let newValue;
do {
newValue = random(arr.length - 1);
} while (newValue === arr[lastIndex]);
arr[lastIndex] = newValue;
return arr[arr[lastIndex]];
}
/**
* @param {any[]} arr
* @return {any}
*/
function pickUnique(arr) {
if (!has(arr, lastIndex)) {
const value = random(arr.length - 1);
_extendArray(arr, value);
return arr[value];
} else {
return _getNextUnique(arr);
}
}
function createUniquePicker(arr) {
_extendArray(arr);
return function () {
return _getNextUnique(arr);
};
}
function _getPassageLines(passage) {
let text;
if (passage.processText) { // we have passage itself
text = passage.processText();
} else { // we have passage name
const rawPassage = Story.get(passage);
if (!rawPassage) {
throw new Error(`No such passage: "${passage}".`);
}
text = rawPassage.processText();
}
return text.split('\n');
}
/**
* @param {string|Passage} passage
* @return {function (): string}
*/
function createUniquePickerFromPassage(passage) {
const arr = _getPassageLines(passage);
return createUniquePicker(arr);
}
window.scUtils = Object.assign(
window.scUtils || {},
{
pickUnique,
createUniquePicker,
createUniquePickerFromPassage,
}
);
}());