/
util.ts
402 lines (352 loc) · 10.7 KB
/
util.ts
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
import {default as clone_} from 'clone';
import deepEqual_ from 'fast-deep-equal';
import stableStringify from 'fast-json-stable-stringify';
import {hasOwnProperty, isNumber, isString, splitAccessPath, stringValue, writeConfig} from 'vega-util';
import {isLogicalAnd, isLogicalNot, isLogicalOr, LogicalComposition} from './logical';
export const deepEqual = deepEqual_;
export const duplicate = clone_;
export function never(message: string): never {
throw new Error(message);
}
/**
* Creates an object composed of the picked object properties.
*
* var object = {'a': 1, 'b': '2', 'c': 3};
* pick(object, ['a', 'c']);
* // → {'a': 1, 'c': 3}
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function pick<T extends object, K extends keyof T>(obj: T, props: readonly K[]): Pick<T, K> {
const copy: any = {};
for (const prop of props) {
if (hasOwnProperty(obj, prop)) {
copy[prop] = obj[prop];
}
}
return copy;
}
/**
* The opposite of _.pick; this method creates an object composed of the own
* and inherited enumerable string keyed properties of object that are not omitted.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function omit<T extends object, K extends keyof T>(obj: T, props: readonly K[]): Omit<T, K> {
const copy = {...(obj as any)};
for (const prop of props) {
delete copy[prop];
}
return copy;
}
/**
* Monkey patch Set so that `stringify` produces a string representation of sets.
*/
Set.prototype['toJSON'] = function () {
return `Set(${[...this].map(x => stableStringify(x)).join(',')})`;
};
/**
* Converts any object to a string representation that can be consumed by humans.
*/
export const stringify = stableStringify;
/**
* Converts any object to a string of limited size, or a number.
*/
export function hash(a: any): string | number {
if (isNumber(a)) {
return a;
}
const str = isString(a) ? a : stableStringify(a);
// short strings can be used as hash directly, longer strings are hashed to reduce memory usage
if (str.length < 250) {
return str;
}
// from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
let h = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
h = (h << 5) - h + char;
h = h & h; // Convert to 32bit integer
}
return h;
}
export function isNullOrFalse(x: any): x is false | null {
return x === false || x === null;
}
export function contains<T>(array: readonly T[], item: T) {
return array.includes(item);
}
/**
* Returns true if any item returns true.
*/
export function some<T>(arr: readonly T[], f: (d: T, k?: any, i?: any) => boolean) {
let i = 0;
for (const [k, a] of arr.entries()) {
if (f(a, k, i++)) {
return true;
}
}
return false;
}
/**
* Returns true if all items return true.
*/
export function every<T>(arr: readonly T[], f: (d: T, k?: any, i?: any) => boolean) {
let i = 0;
for (const [k, a] of arr.entries()) {
if (!f(a, k, i++)) {
return false;
}
}
return true;
}
/**
* Like TS Partial but applies recursively to all properties.
*/
export type DeepPartial<T> = {[P in keyof T]?: DeepPartial<T[P]>};
/**
* recursively merges src into dest
*/
export function mergeDeep<T>(dest: T, ...src: readonly DeepPartial<T>[]): T {
for (const s of src) {
deepMerge_(dest, s ?? {});
}
return dest;
}
function deepMerge_(dest: any, src: any) {
for (const property of keys(src)) {
writeConfig(dest, property, src[property], true);
}
}
export function unique<T>(values: readonly T[], f: (item: T) => string | number): T[] {
const results: T[] = [];
const u = {};
let v: string | number;
for (const val of values) {
v = f(val);
if (v in u) {
continue;
}
u[v] = 1;
results.push(val);
}
return results;
}
export type Dict<T> = Record<string, T>;
/**
* Returns true if the two dictionaries disagree. Applies only to defined values.
*/
export function isEqual<T>(dict: Dict<T>, other: Dict<T>) {
const dictKeys = keys(dict);
const otherKeys = keys(other);
if (dictKeys.length !== otherKeys.length) {
return false;
}
for (const key of dictKeys) {
if (dict[key] !== other[key]) {
return false;
}
}
return true;
}
export function setEqual<T>(a: Set<T>, b: Set<T>) {
if (a.size !== b.size) {
return false;
}
for (const e of a) {
if (!b.has(e)) {
return false;
}
}
return true;
}
export function hasIntersection<T>(a: ReadonlySet<T>, b: ReadonlySet<T>) {
for (const key of a) {
if (b.has(key)) {
return true;
}
}
return false;
}
export function prefixGenerator(a: ReadonlySet<string>): ReadonlySet<string> {
const prefixes = new Set<string>();
for (const x of a) {
const splitField = splitAccessPath(x);
// Wrap every element other than the first in `[]`
const wrappedWithAccessors = splitField.map((y, i) => (i === 0 ? y : `[${y}]`));
const computedPrefixes = wrappedWithAccessors.map((_, i) => wrappedWithAccessors.slice(0, i + 1).join(''));
for (const y of computedPrefixes) {
prefixes.add(y);
}
}
return prefixes;
}
/**
* Returns true if a and b have an intersection. Also return true if a or b are undefined
* since this means we don't know what fields a node produces or depends on.
*/
export function fieldIntersection(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
if (a === undefined || b === undefined) {
return true;
}
return hasIntersection(prefixGenerator(a), prefixGenerator(b));
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function isEmpty(obj: object) {
return keys(obj).length === 0;
}
// This is a stricter version of Object.keys but with better types. See https://github.com/Microsoft/TypeScript/pull/12253#issuecomment-263132208
export const keys = Object.keys as <T>(o: T) => Extract<keyof T, string>[];
export const vals = Object.values;
export const entries = Object.entries;
// Using mapped type to declare a collect of flags for a string literal type S
// https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types
export type Flag<S extends string> = {[K in S]: 1};
export function isBoolean(b: any): b is boolean {
return b === true || b === false;
}
/**
* Convert a string into a valid variable name
*/
export function varName(s: string): string {
// Replace non-alphanumeric characters (anything besides a-zA-Z0-9_) with _
const alphanumericS = s.replace(/\W/g, '_');
// Add _ if the string has leading numbers.
return (s.match(/^\d+/) ? '_' : '') + alphanumericS;
}
export function logicalExpr<T>(op: LogicalComposition<T>, cb: (...args: readonly any[]) => string): string {
if (isLogicalNot(op)) {
return `!(${logicalExpr(op.not, cb)})`;
} else if (isLogicalAnd(op)) {
return `(${op.and.map((and: LogicalComposition<T>) => logicalExpr(and, cb)).join(') && (')})`;
} else if (isLogicalOr(op)) {
return `(${op.or.map((or: LogicalComposition<T>) => logicalExpr(or, cb)).join(') || (')})`;
} else {
return cb(op);
}
}
/**
* Delete nested property of an object, and delete the ancestors of the property if they become empty.
*/
export function deleteNestedProperty(obj: any, orderedProps: string[]) {
if (orderedProps.length === 0) {
return true;
}
const prop = orderedProps.shift()!; // eslint-disable-line @typescript-eslint/no-non-null-assertion
if (prop in obj && deleteNestedProperty(obj[prop], orderedProps)) {
delete obj[prop];
}
return isEmpty(obj);
}
export function titleCase(s: string) {
return s.charAt(0).toUpperCase() + s.substr(1);
}
/**
* Converts a path to an access path with datum.
* @param path The field name.
* @param datum The string to use for `datum`.
*/
export function accessPathWithDatum(path: string, datum = 'datum') {
const pieces = splitAccessPath(path);
const prefixes = [];
for (let i = 1; i <= pieces.length; i++) {
const prefix = `[${pieces.slice(0, i).map(stringValue).join('][')}]`;
prefixes.push(`${datum}${prefix}`);
}
return prefixes.join(' && ');
}
/**
* Return access with datum to the flattened field.
*
* @param path The field name.
* @param datum The string to use for `datum`.
*/
export function flatAccessWithDatum(path: string, datum: 'datum' | 'parent' | 'datum.datum' = 'datum') {
return `${datum}[${stringValue(splitAccessPath(path).join('.'))}]`;
}
function escapePathAccess(string: string) {
return string.replace(/(\[|\]|\.|'|")/g, '\\$1');
}
/**
* Replaces path accesses with access to non-nested field.
* For example, `foo["bar"].baz` becomes `foo\\.bar\\.baz`.
*/
export function replacePathInField(path: string) {
return `${splitAccessPath(path).map(escapePathAccess).join('\\.')}`;
}
/**
* Replace all occurrences of a string with another string.
*
* @param string the string to replace in
* @param find the string to replace
* @param replacement the replacement
*/
export function replaceAll(string: string, find: string, replacement: string) {
return string.replace(new RegExp(find.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replacement);
}
/**
* Remove path accesses with access from field.
* For example, `foo["bar"].baz` becomes `foo.bar.baz`.
*/
export function removePathFromField(path: string) {
return `${splitAccessPath(path).join('.')}`;
}
/**
* Count the depth of the path. Returns 1 for fields that are not nested.
*/
export function accessPathDepth(path: string) {
if (!path) {
return 0;
}
return splitAccessPath(path).length;
}
/**
* This is a replacement for chained || for numeric properties or properties that respect null so that 0 will be included.
*/
export function getFirstDefined<T>(...args: readonly T[]): T | undefined {
for (const arg of args) {
if (arg !== undefined) {
return arg;
}
}
return undefined;
}
// variable used to generate id
let idCounter = 42;
/**
* Returns a new random id every time it gets called.
*
* Has side effect!
*/
export function uniqueId(prefix?: string) {
const id = ++idCounter;
return prefix ? String(prefix) + id : id;
}
/**
* Resets the id counter used in uniqueId. This can be useful for testing.
*/
export function resetIdCounter() {
idCounter = 42;
}
export function internalField(name: string) {
return isInternalField(name) ? name : `__${name}`;
}
export function isInternalField(name: string) {
return name.startsWith('__');
}
/**
* Normalize angle to be within [0,360).
*/
export function normalizeAngle(angle: number) {
if (angle === undefined) {
return undefined;
}
return ((angle % 360) + 360) % 360;
}
/**
* Returns whether the passed in value is a valid number.
*/
export function isNumeric(value: number | string): boolean {
if (isNumber(value)) {
return true;
}
return !isNaN(value as any) && !isNaN(parseFloat(value));
}