-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneral.ts
More file actions
251 lines (216 loc) · 8.29 KB
/
general.ts
File metadata and controls
251 lines (216 loc) · 8.29 KB
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
import { capitalizeFirst, capitalizeFirstPerWord, caseType } from "./case-types-parser";
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
/**
* Safely access obj[key], throwing on prototype-pollution keys.
* Use when key is a variable (e.g. from a loop) to prevent __proto__/constructor/prototype injection.
* @param obj - Object to read from
* @param key - Property key (string or number)
* @returns The value at obj[key]
*/
export function safeAccess(obj: any, key: string | number): any {
if (typeof key === 'string' && UNSAFE_KEYS.has(key)) {
throw new Error(`Unsafe key rejected: ${key}`);
}
return obj[key];
}
/**
* Safely set obj[key] = value, throwing on prototype-pollution keys.
* Use when key is a variable to prevent __proto__/constructor/prototype injection.
* @param obj - Object to write to
* @param key - Property key (string or number)
* @param value - Value to set
*/
export function safeSet(obj: any, key: string | number, value: any): void {
if (typeof key === 'string' && UNSAFE_KEYS.has(key)) {
throw new Error(`Unsafe key rejected: ${key}`);
}
obj[key] = value;
}
export function jsonCopy(src: any): any {
return JSON.parse(JSON.stringify(src));
}
export function arrayToDict(array: any[], key: string, targetKey?: string): { [key: string]: any } {
if (!targetKey) {
return array.reduce((acc: any, entry: any) => {
acc[getKeyValue(entry, key)] = entry;
return acc;
}, {});
} else return arrayToDictWithKeys(array, key, [targetKey]);
}
export function arrayToDictWithKeys(array: any[], key: string, targetKey: string[]): { [key: string]: any } {
if (targetKey.length === 1) {
return array.reduce((acc: any, entry: any) => {
acc[getKeyValue(entry, key)] = getKeyValue(entry, targetKey[0]);
return acc;
}, {});
}
else {
return array.reduce((acc: any, entry: any) => {
const target: any = {};
targetKey.forEach((key: string) => {
target[getKeyName(key)] = getKeyValue(entry, key);
});
acc[getKeyValue(entry, key)] = target;
return acc;
}, {});
}
}
function getKeyValue(obj: any, key: string) {
const keys = key.split('.');
let target = obj;
keys.forEach((key: string) => {
target = safeAccess(target, key);
});
return target;
}
function getKeyName(key: string) {
const keys = key.split('.');
return keys[keys.length - 1];
}
export function combineClassNames(...classes: string[]) {
return classes.filter(Boolean).join(' ')
}
const TRUE_VALUES = ['true', '1', 'yes', 'y', 'on', 'x'];
export function isStringTrue(value: string): boolean {
if (!value) return false;
value = value.toLowerCase();
return TRUE_VALUES.includes(value);
}
export function copyToClipboard(textToCopy: string) {
navigator.clipboard.writeText(textToCopy);
}
/**
* transfer values from dictA to dictB, if the key is not present in dictB, it will be ignored or created.
* @param {dictionary[]} dictA holds data that should be transferred.
* @param {dictionary[]} dictB holds data that should be overwritten if existing in dictA.
* @param {boolean} ignoreNoneExistingKeys - optional - decides weather none existent keys are created or ignored.
*/
export function transferNestedDict(dictA: any, dictB: any, ignoreNoneExistingKeys: boolean = true) {
if (dictA == null || dictB == null) return;
if (typeof dictA !== 'object' || typeof dictB !== 'object') return;
for (let key in dictA) {
if (dictB[key] == null && ignoreNoneExistingKeys) continue;
if (Array.isArray(dictA[key])) {
dictB[key] = dictA[key];
}
else if (typeof dictA[key] === 'object' && dictA[key] !== null) {
if (typeof dictB[key] !== 'object') {
dictB[key] = {};
}
transferNestedDict(dictA[key], dictB[key], ignoreNoneExistingKeys);
} else {
dictB[key] = dictA[key];
}
}
}
export function loopNestedDict(dict: any, callback: (key: string, value: any) => void) {
for (let key in dict) {
if (typeof dict[key] === 'object') {
loopNestedDict(dict[key], callback);
} else {
callback(key, dict[key]);
}
}
}
export function tryParseJSON(str: string): any {
try {
return JSON.parse(str);
} catch (e) {
return null;
}
}
export function formatBytes(bytes: number, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return parseFloat((bytes / Math.pow(1024, i)).toFixed(dm)) + ' ' + sizes[i];
}
export type enumToArrayOptions = {
caseType?: caseType;
prefix?: string;
nameFunction?: (name: any) => string;
}
export function enumToArray(e: Object, options: enumToArrayOptions | null = null): any[] {
const arr = Object.values(e);
if (!options) return sortByEnumPos(e, arr);
let func;
if (options.caseType == caseType.LOWER) func = (x: any) => x.toLowerCase();
else if (options.caseType == caseType.UPPER) func = (x: any) => x.toUpperCase();
else if (options.caseType == caseType.CAPITALIZE_FIRST) func = capitalizeFirst;
else if (options.caseType == caseType.CAPITALIZE_FIRST_PER_WORD) func = capitalizeFirstPerWord;
if (func) return enumToArray(e, { prefix: options.prefix, nameFunction: func });
if (!options.nameFunction) return sortByEnumPos(e, arr.map(x => ({ name: options.prefix + x, value: x })));
return sortByEnumPos(e, arr.map(x => ({ name: (options.prefix ? options.prefix : "") + options.nameFunction(x), value: x })));
}
function sortByEnumPos(e: any, arr: any[]) {
const order: string[] = [];
for (let key in e) {
order.push(key);
}
return arr.sort((a, b) => {
const index1 = order.findIndex(key => e[key] === a.code);
const index2 = order.findIndex(key => e[key] === b.code);
return index1 - index2;
});
}
const ESCAPE_CHARACTERS = ['\n', '\r', '\t'];
const ESCAPE_CHARACTERS_STRING = ['\\n', '\\r', '\\t'];
export function hasPreEscapeCharacters(str: string): boolean {
return ESCAPE_CHARACTERS.some(char => str.includes(char));
}
export function replaceStringEscapeCharacters(str: string, toEscaped: boolean = true): string {
if (toEscaped) {
ESCAPE_CHARACTERS.forEach((char, index) => {
str = str.replace(char, ESCAPE_CHARACTERS_STRING[index]);
});
} else {
ESCAPE_CHARACTERS_STRING.forEach((char, index) => {
str = str.replace(char, ESCAPE_CHARACTERS[index]);
});
}
return str;
}
export function countOccurrences(str: string, search: string): number {
let c = 0, p = -1;
while (true) {
p = str.indexOf(search, p + 1)
if (p != -1) c++;
else break;
}
return c;
}
export function removeArrayFromArray(mainArray: any[], arrayToRemove: any[]) {
return mainArray.filter((element) => !arrayToRemove.includes(element));
}
export function objectIsEmpty(obj: any): boolean {
if (!obj) return true;
for (var i in obj) return false;
return true;
}
export function getUserAvatarUri(user, prefix?: string) {
let avatarId = 0;
if (user && user.firstName && user.lastName) {
avatarId = (user.firstName[0].charCodeAt(0) + user.lastName[0].charCodeAt(0)) % 5;
}
if (prefix) return prefix + avatarId + ".png";
return avatarId + ".png";
}
export function percentRoundString(value: number | string, decimals: number = 0, isZeroToOne: boolean = true) {
if (typeof value == 'number') {
if (isNaN(value)) return "n/a";
if (!isFinite(value)) return "0 %";
if (isZeroToOne) value *= 100;
if (!decimals) return Math.round(value) + ' %';
const dec = 10 ** decimals;
return Math.round(value * dec) / dec + ' %';
}
else if (typeof value == 'undefined' || value == null) return "n/a";
return value;
}
export function isDict(o: any): boolean {
return o === Object(o) && !Array.isArray(o) && typeof o !== 'function';
}
export function objectDepth(o) {
return Object(o) === o ? 1 + Math.max(-1, ...Object.values(o).map(objectDepth)) : 0
}