-
Notifications
You must be signed in to change notification settings - Fork 4
/
lib.mjs
131 lines (120 loc) · 2.28 KB
/
lib.mjs
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
/**
* Randomize array element order in-place.
* Using Durstenfeld shuffle algorithm.
* @param {any[]} array
*/
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function isString(maybe) {
return (typeof maybe) === 'string';
}
function isUndefined(value) {
return value === undefined;
}
/**
*
* @param {number} min
* @param {number} max
* @return {number} [min, max)
*/
function getRandomInt(min, max) {
let fix = 0;
if (min < 0) {
fix = min;
min = 0;
max -= fix;
}
return Math.floor(Math.random() * (max - min)) + min + fix;
}
/**
* 返回一个列表 [start, end)
* @param {number} start
* @param {number} end
* @return {number[]}
*/
function range(start, end) {
const ret = [];
while (start < end) {
ret.push(start);
start += 1;
}
return ret;
}
/**
* 分割数组里面的元素
* @param {number[]} list
* @param {number} num 要分割成几份
* @return {number[][]}
*/
function splitArray(list, num) {
const indexList = range(1, list.length);
shuffleArray(indexList);
const usedIndex = indexList.slice(0, num - 1).sort();
const ret = [];
let start = 0;
usedIndex.forEach((value) => {
ret.push(list.slice(start, value));
start = value;
});
ret.push(list.slice(start));
return ret;
}
let _global;
try {
_global = global;
} catch (error) {
_global = window;
}
function valueOf(expStr, getValue) {
const func = new Function('env', `with(env){return ${expStr}}`);
const env = new Proxy({}, {
get: function(_, key){
const value = getValue(key);
return (isUndefined(value) ? _global[key] : value);
},
has: function (_, key) {
return true;
},
});
return func(env);
}
/**
*
* @param {any[]} arr
* @param {any} item
*/
function removeItem(arr, item) {
const index = arr.indexOf(item);
if (index >= 0) {
arr.splice(index, 1);
}
}
const Flag = {
shuffle: 'shuffle',
link: 'link',
unlink: 'unlink',
};
const Type = {
int: 'int',
set: 'set',
graph: 'graph',
alias: 'alias',
};
export {
shuffleArray,
getRandomInt,
isString,
valueOf,
range,
splitArray,
removeItem,
Flag,
Type,
}