@tutao/tutanota-utils 3.89.24 → 3.91.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/Utils.js DELETED
@@ -1,416 +0,0 @@
1
- // @flow
2
- import {TypeRef} from "./TypeRef"
3
-
4
-
5
- export type lazy<T> = () => T;
6
- export type lazyAsync<T> = () => Promise<T>;
7
- export type Thunk = () => mixed
8
-
9
- export type DeferredObject<T> = {
10
- resolve: (T) => void,
11
- reject: (Error) => void,
12
- promise: Promise<T>,
13
- }
14
-
15
- export type DeferredObjectWithHandler<T, U> = {
16
- resolve: (T) => void,
17
- reject: (Error) => void,
18
- promise: Promise<U>,
19
- }
20
-
21
- export function defer<T>(): DeferredObject<T> {
22
- let ret = {}
23
- ret.promise = new Promise((resolve, reject) => {
24
- ret.resolve = resolve
25
- ret.reject = reject
26
- })
27
- return ret
28
- }
29
-
30
- export function deferWithHandler<T, U>(handler: T => U): DeferredObjectWithHandler<T, U> {
31
- const deferred = {}
32
- deferred.promise = new Promise((resolve, reject) => {
33
- deferred.resolve = resolve
34
- deferred.reject = reject
35
- }).then(handler)
36
- return deferred
37
- }
38
-
39
- export async function asyncFind<T>(
40
- array: $ReadOnlyArray<T>,
41
- finder: (item: T, index: number, arrayLength: number) => Promise<boolean>
42
- ): Promise<?T> {
43
- for (let i = 0; i < array.length; i++) {
44
- const item = array[i]
45
- if (await finder(item, i, array.length)) {
46
- return item
47
- }
48
- }
49
- return null
50
- }
51
-
52
- export async function asyncFindAndMap<T, R>(
53
- array: $ReadOnlyArray<T>,
54
- finder: (item: T, index: number, arrayLength: number) => Promise<?R>
55
- ): Promise<?R> {
56
- for (let i = 0; i < array.length; i++) {
57
- const item = array[i]
58
- const mapped = await finder(item, i, array.length)
59
- if (mapped) {
60
- return mapped
61
- }
62
- }
63
- return null
64
- }
65
-
66
- /**
67
- * Calls an executor function for slices of nbrOfElementsInGroup items of the given array until the executor function returns false.
68
- */
69
- export function executeInGroups<T>(array: T[], nbrOfElementsInGroup: number, executor: (items: T[]) => Promise<boolean>): Promise<void> {
70
- if (array.length > 0) {
71
- let nextSlice = Math.min(array.length, nbrOfElementsInGroup)
72
- return executor(array.slice(0, nextSlice)).then(doContinue => {
73
- if (doContinue) {
74
- return executeInGroups(array.slice(nextSlice), nbrOfElementsInGroup, executor)
75
- }
76
- })
77
- } else {
78
- return Promise.resolve()
79
- }
80
- }
81
-
82
- export function neverNull<T>(object: ?T): T {
83
- return (object: any)
84
- }
85
-
86
- export function assertNotNull<T>(object: ?T, message: string = "null"): T {
87
- if (object == null) {
88
- throw new Error("AssertNotNull failed : " + message)
89
- }
90
- return object
91
- }
92
-
93
- export function assert(assertion: MaybeLazy<boolean>, message: string) {
94
- if (!resolveMaybeLazy(assertion)) {
95
- throw new Error(`Assertion failed: ${message}`)
96
- }
97
- }
98
-
99
- export function downcast<R>(object: *): R {
100
- return (object: any)
101
- }
102
-
103
- export function clone<T>(instance: T): T {
104
- if (instance instanceof Uint8Array) {
105
- return downcast<T>(instance.slice())
106
- } else if (instance instanceof Array) {
107
- return downcast<T>(instance.map(i => clone(i)))
108
- } else if (instance instanceof Date) {
109
- return (new Date(instance.getTime()): any)
110
- } else if (instance instanceof TypeRef) {
111
- return instance
112
- } else if (instance instanceof Object) {
113
- // Can only pass null or Object, cannot pass undefined
114
- const copy = Object.create(Object.getPrototypeOf(instance) || null)
115
- Object.assign(copy, instance)
116
- for (let key of Object.keys(copy)) {
117
- copy[key] = clone(copy[key])
118
- }
119
- return (copy: any)
120
- } else {
121
- return instance
122
- }
123
- }
124
-
125
- /**
126
- * Function which accepts another function. On first invocation
127
- * of this resulting function result will be remembered and returned
128
- * on consequent invocations.
129
- */
130
- export function lazyMemoized<T>(source: () => T): () => T {
131
- // Using separate variable for tracking because value can be undefined and we want to the function call only once
132
- let cached = false
133
- let value
134
- return () => {
135
- if (cached) {
136
- return value
137
- } else {
138
- cached = true
139
- return value = source()
140
- }
141
- }
142
- }
143
-
144
- /**
145
- * Returns a cached version of {@param fn}.
146
- * Cached function checks that argument is the same (with ===) and if it is then it returns the cached result.
147
- * If the cached argument has changed then {@param fn} will be called with new argument and result will be cached again.
148
- * Only remembers the last argument.
149
- */
150
- export function memoized<T, R>(fn: (T) => R): (T) => R {
151
- let lastArg: T
152
- let lastResult: R
153
- let didCache = false
154
- return (arg) => {
155
- if (!didCache || arg !== lastArg) {
156
- lastArg = arg
157
- didCache = true
158
- lastResult = fn(arg)
159
- }
160
- return lastResult
161
- }
162
- }
163
-
164
- /**
165
- * Function which returns what was passed into it
166
- */
167
- export function identity<T>(t: T): T {
168
- return t
169
- }
170
-
171
- /**
172
- * Function which does nothing.
173
- */
174
- export function noOp() {}
175
-
176
- /**
177
- * Return a function, which executed {@param toThrottle} only after it is not invoked for {@param timeout} ms.
178
- * Executes function with the last passed arguments
179
- * @return {Function}
180
- */
181
- export function debounce<F: (...args: any) => void>(timeout: number, toThrottle: F): F {
182
- let timeoutId
183
- let toInvoke: (...args: any) => void;
184
- return downcast((...args) => {
185
- if (timeoutId) {
186
- clearTimeout(timeoutId)
187
- }
188
- toInvoke = toThrottle.bind(null, ...args)
189
- timeoutId = setTimeout(toInvoke, timeout)
190
- })
191
- }
192
-
193
- /**
194
- * Returns a debounced function. When invoked for the first time, will just invoke
195
- * {@param toThrottle}. On subsequent invocations it will either invoke it right away
196
- * (if {@param timeout} has passed) or will schedule it to be run after {@param timeout}.
197
- * So the first and the last invocations in a series of invocations always take place
198
- * but ones in the middle (which happen too often) are discarded.}
199
- */
200
- export function debounceStart<F: (...args: any) => void>(timeout: number, toThrottle: F): F {
201
- let timeoutId: ?TimeoutID
202
- let lastInvoked = 0
203
- return downcast((...args: any) => {
204
- if (Date.now() - lastInvoked < timeout) {
205
- timeoutId && clearTimeout(timeoutId)
206
- timeoutId = setTimeout(() => {
207
- timeoutId = null
208
- toThrottle.apply(null, args)
209
- }, timeout)
210
- } else {
211
- toThrottle.apply(null, args)
212
- }
213
- lastInvoked = Date.now()
214
- })
215
- }
216
-
217
- export function randomIntFromInterval(min: number, max: number): number {
218
- return Math.floor(Math.random() * (max - min + 1) + min);
219
- }
220
-
221
- export function errorToString(error: Error): string {
222
- let errorString = error.name ? error.name : "?"
223
- if (error.message) {
224
- errorString += `\n Error message: ${error.message}`
225
- }
226
- if (error.stack) {
227
- // the error id is included in the stacktrace
228
- errorString += `\nStacktrace: \n${error.stack}`
229
- }
230
- return errorString
231
- }
232
-
233
- /**
234
- * Like {@link Object.entries} but preserves the type of the key and value
235
- */
236
- export function objectEntries<A: (string | Symbol), B>(object: {[A]: B}): Array<[A, B]> {
237
- return downcast(Object.entries(object))
238
- }
239
-
240
- /**
241
- * modified deepEquals from ospec is only needed as long as we use custom classes (TypeRef) and Date is not properly handled
242
- */
243
- export function deepEqual(a: any, b: any): boolean {
244
- if (a === b) return true
245
- if (xor(a === null, b === null) || xor(a === undefined, b === undefined)) return false
246
- if (typeof a === "object" && typeof b === "object") {
247
- const aIsArgs = isArguments(a), bIsArgs = isArguments(b)
248
- if (a.length === b.length && (a instanceof Array && b instanceof Array || aIsArgs && bIsArgs)) {
249
- const aKeys = Object.getOwnPropertyNames(a), bKeys = Object.getOwnPropertyNames(b)
250
- if (aKeys.length !== bKeys.length) return false
251
- for (let i = 0; i < aKeys.length; i++) {
252
- if (!hasOwn.call(b, aKeys[i]) || !deepEqual(a[aKeys[i]], b[aKeys[i]])) return false
253
- }
254
- return true
255
- }
256
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
257
- if (a instanceof Object && b instanceof Object && !aIsArgs && !bIsArgs) {
258
- for (let i in a) {
259
- if ((!(i in b)) || !deepEqual(a[i], b[i])) return false
260
- }
261
- for (let i in b) {
262
- if (!(i in a)) return false
263
- }
264
- return true
265
- }
266
- if (typeof Buffer === "function" && a instanceof Buffer && b instanceof Buffer) {
267
- for (let i = 0; i < a.length; i++) {
268
- if (a[i] !== b[i]) return false
269
- }
270
- return true
271
- }
272
- if (a.valueOf() === b.valueOf()) return true
273
- }
274
- return false
275
- }
276
-
277
- function xor(a, b): boolean {
278
- const aBool = !!a
279
- const bBool = !!b
280
- return (aBool && !bBool) || (bBool && !aBool)
281
- }
282
-
283
- function isArguments(a) {
284
- if ("callee" in a) {
285
- for (let i in a) if (i === "callee") return false
286
- return true
287
- }
288
- }
289
-
290
- const hasOwn = ({}).hasOwnProperty
291
-
292
- /**
293
- * returns an array of top-level properties that are in both objA and objB, but differ in value
294
- * does not handle functions or circular references
295
- * treats undefined and null as equal
296
- */
297
- export function getChangedProps(objA: any, objB: any): Array<string> {
298
- if (objA == null || objB == null || objA === objB) return []
299
- return Object.keys(objA)
300
- .filter(k => Object.keys(objB).includes(k))
301
- .filter(k => ![null, undefined].includes(objA[k]) || ![null, undefined].includes(objB[k]))
302
- .filter(k => !deepEqual(objA[k], objB[k]))
303
- }
304
-
305
- /**
306
- * Disallow set, delete and clear on Map.
307
- * Important: It is *not* a deep freeze.
308
- * @param myMap
309
- * @return {unknown}
310
- */
311
- export function freezeMap<K, V>(myMap: Map<K, V>): Map<K, V> {
312
- function mapSet(key) {
313
- throw new Error('Can\'t add property ' + key + ', map is not extensible')
314
- }
315
-
316
- function mapDelete(key) {
317
- throw new Error('Can\'t delete property ' + key + ', map is frozen')
318
- }
319
-
320
- function mapClear() {
321
- throw new Error('Can\'t clear map, map is frozen')
322
- }
323
-
324
- const anyMap = downcast(myMap)
325
- anyMap.set = mapSet
326
- anyMap.delete = mapDelete
327
- anyMap.clear = mapClear
328
-
329
- Object.freeze(anyMap)
330
-
331
- return anyMap
332
- }
333
-
334
- export function addressDomain(senderAddress: string): string {
335
- return senderAddress.slice(senderAddress.lastIndexOf("@") + 1)
336
- }
337
-
338
- /**
339
- * Ignores the fact that Object.keys returns also not owned properties.
340
- */
341
- export function typedKeys<K: string, V>(obj: {[K]: V}): Array<K> {
342
- return downcast(Object.keys(obj))
343
- }
344
-
345
- /**
346
- * Ignores the fact that Object.keys returns also not owned properties.
347
- */
348
- export function typedEntries<K: string, V>(obj: {[K]: V}): Array<[K, V]> {
349
- return downcast(Object.entries(obj))
350
- }
351
-
352
- /**
353
- * Ignores the fact that Object.keys returns also not owned properties.
354
- */
355
- export function typedValues<K: string, V>(obj: {[K]: V}): Array<V> {
356
- return downcast(Object.values(obj))
357
- }
358
-
359
- export type MaybeLazy<T> = T | lazy<T>;
360
-
361
- export function resolveMaybeLazy<T>(maybe: MaybeLazy<T>): T {
362
- return (typeof maybe === "function" ? downcast(maybe)() : maybe)
363
- }
364
-
365
- export function getAsLazy<T>(maybe: MaybeLazy<T>): lazy<T> {
366
- return (typeof maybe === "function" ? downcast(maybe) : () => maybe)
367
- }
368
-
369
- export function mapLazily<T, U>(maybe: MaybeLazy<T>, mapping: (T) => U): lazy<U> {
370
- return () => mapping(resolveMaybeLazy(maybe))
371
- }
372
-
373
- /**
374
- * Stricter version of parseInt() from MDN. parseInt() allows some arbitrary characters at the end of the string.
375
- * Returns NaN in case there's anything non-number in the string.
376
- */
377
- export function filterInt(value: string): number {
378
- if (/^\d+$/.test(value)) {
379
- return parseInt(value, 10);
380
- } else {
381
- return NaN;
382
- }
383
- }
384
-
385
- interface Positioned {
386
- x: number,
387
- y: number,
388
- }
389
-
390
- interface Sized {
391
- top: number,
392
- left: number,
393
- bottom: number,
394
- right: number,
395
- }
396
-
397
- export function insideRect(point: Positioned, rect: Sized): boolean {
398
- return point.x >= rect.left && point.x < rect.right
399
- && point.y >= rect.top && point.y < rect.bottom
400
- }
401
-
402
- /**
403
- * If val is non null, returns the result of val passed to action, else null
404
- */
405
- export function mapNullable<T, U>(val: ?T, action: T => ?U): U | null {
406
- if (val != null) {
407
- const result = action(val)
408
- if (result != null) {
409
- return result
410
- }
411
- }
412
- return null
413
- }
414
-
415
- /** Helper to take instead of `typeof setTimeout` which is hellish to reproduce */
416
- export type TimeoutSetter = (fn: () => mixed, number) => TimeoutID
package/lib/index.js DELETED
@@ -1,207 +0,0 @@
1
- // @flow
2
- export {
3
- concat,
4
- numberRange,
5
- arrayEquals,
6
- arrayEqualsWithPredicate,
7
- arrayHash,
8
- remove,
9
- findAll,
10
- findAndRemove,
11
- findAllAndRemove,
12
- replace,
13
- mapAndFilterNull,
14
- filterNull,
15
- last,
16
- isEmpty,
17
- lastThrow,
18
- firstThrow,
19
- first,
20
- findLast,
21
- findLastIndex,
22
- contains,
23
- addAll,
24
- removeAll,
25
- groupByAndMapUniquely,
26
- groupByAndMap,
27
- groupBy,
28
- splitInChunks,
29
- flat,
30
- flatMap,
31
- insertIntoSortedArray,
32
- zip,
33
- deduplicate,
34
- binarySearch,
35
- lastIndex,
36
- union,
37
- difference,
38
- symmetricDifference,
39
- partition,
40
- } from "./ArrayUtils"
41
-
42
- export {
43
- AsyncResult,
44
- } from "./AsyncResult"
45
-
46
- export {
47
- intersection,
48
- } from "./CollectionUtils"
49
-
50
- export {
51
- DAY_IN_MILLIS,
52
- getStartOfNextDay,
53
- getEndOfDay,
54
- getStartOfDay,
55
- getHourOfDay,
56
- isStartOfDay,
57
- isToday,
58
- isSameDay,
59
- getDayShifted,
60
- incrementDate,
61
- incrementMonth,
62
- isSameDayOfDate,
63
- formatSortableDate,
64
- formatSortableDateTime,
65
- sortableTimestamp,
66
- isValidDate,
67
- millisToDays,
68
- daysToMillis,
69
- } from "./DateUtils"
70
-
71
- export {
72
- uint8ArrayToArrayBuffer,
73
- hexToBase64,
74
- base64ToHex,
75
- base64ToBase64Url,
76
- base64ToBase64Ext,
77
- base64ExtToBase64,
78
- base64UrlToBase64,
79
- stringToUtf8Uint8Array,
80
- utf8Uint8ArrayToString,
81
- hexToUint8Array,
82
- uint8ArrayToHex,
83
- uint8ArrayToBase64,
84
- int8ArrayToBase64,
85
- base64ToUint8Array,
86
- uint8ArrayToString,
87
- decodeQuotedPrintable,
88
- decodeBase64,
89
- stringToBase64,
90
- } from "./Encoding"
91
-
92
- export type {
93
- Base64,
94
- Base64Ext,
95
- Base64Url,
96
- Hex
97
- } from "./Encoding"
98
-
99
- export {
100
- LazyLoaded
101
- } from "./LazyLoaded"
102
-
103
- export {
104
- mergeMaps,
105
- getFromMap,
106
- addMapEntry,
107
- deleteMapEntry,
108
- } from "./MapUtils"
109
-
110
- export {
111
- pMap,
112
- } from "./PromiseMap"
113
-
114
- export type {
115
- Mapper,
116
- } from "./PromiseMap"
117
-
118
- export {
119
- mapInCallContext,
120
- promiseMap,
121
- promiseMapCompat,
122
- PromisableWrapper,
123
- delay,
124
- tap,
125
- ofClass,
126
- promiseFilter,
127
- } from "./PromiseUtils"
128
-
129
- export type {
130
- PromiseMapFn,
131
- $Promisable
132
- } from "./PromiseUtils"
133
-
134
- export {
135
- SortedArray,
136
- } from "./SortedArray"
137
-
138
- export type {
139
- CompareFn
140
- } from "./SortedArray"
141
-
142
- export {
143
- pad,
144
- startsWith,
145
- capitalizeFirstLetter,
146
- endsWith,
147
- lazyStringValue,
148
- repeat,
149
- cleanMatch,
150
- NBSP,
151
- splitAt,
152
- toLowerCase,
153
- localeCompare,
154
- byteLength,
155
- replaceAll,
156
- } from "./StringUtils"
157
-
158
- export {
159
- TypeRef,
160
- isSameTypeRefByAttr,
161
- isSameTypeRef
162
- } from "./TypeRef"
163
-
164
- export {
165
- defer,
166
- deferWithHandler,
167
- asyncFind,
168
- asyncFindAndMap,
169
- executeInGroups,
170
- neverNull,
171
- assertNotNull,
172
- assert,
173
- downcast,
174
- clone,
175
- lazyMemoized,
176
- memoized,
177
- identity,
178
- noOp,
179
- debounce,
180
- debounceStart,
181
- randomIntFromInterval,
182
- errorToString,
183
- objectEntries,
184
- deepEqual,
185
- getChangedProps,
186
- freezeMap,
187
- addressDomain,
188
- typedKeys,
189
- typedEntries,
190
- typedValues,
191
- resolveMaybeLazy,
192
- getAsLazy,
193
- mapLazily,
194
- filterInt,
195
- insideRect,
196
- mapNullable,
197
- } from "./Utils"
198
-
199
- export type {
200
- DeferredObject,
201
- lazy,
202
- lazyAsync,
203
- Thunk,
204
- DeferredObjectWithHandler,
205
- MaybeLazy,
206
- TimeoutSetter
207
- } from "./Utils"