-
Notifications
You must be signed in to change notification settings - Fork 592
/
util.js
385 lines (385 loc) · 10.2 KB
/
util.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
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
import { default as clone_ } from 'clone';
import deepEqual_ from 'fast-deep-equal';
import stableStringify from 'fast-json-stable-stringify';
import { isArray, isNumber, isString, splitAccessPath, stringValue } from 'vega-util';
import { isLogicalAnd, isLogicalNot, isLogicalOr } from './logical';
export const deepEqual = deepEqual_;
export const duplicate = clone_;
/**
* 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}
*
*/
export function pick(obj, props) {
const copy = {};
for (const prop of props) {
if (obj.hasOwnProperty(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.
*/
export function omit(obj, props) {
const copy = Object.assign({}, obj);
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) {
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) {
return x === false || x === null;
}
export function contains(array, item) {
return array.indexOf(item) > -1;
}
/** Returns the array without the elements in item */
export function without(array, excludedItems) {
return array.filter(item => !contains(excludedItems, item));
}
export function union(array, other) {
return array.concat(without(other, array));
}
/**
* Returns true if any item returns true.
*/
export function some(arr, f) {
let i = 0;
for (let k = 0; k < arr.length; k++) {
if (f(arr[k], k, i++)) {
return true;
}
}
return false;
}
/**
* Returns true if all items return true.
*/
export function every(arr, f) {
let i = 0;
for (let k = 0; k < arr.length; k++) {
if (!f(arr[k], k, i++)) {
return false;
}
}
return true;
}
export function flatten(arrays) {
return [].concat(...arrays);
}
export function fill(val, len) {
const arr = new Array(len);
for (let i = 0; i < len; ++i) {
arr[i] = val;
}
return arr;
}
/**
* recursively merges src into dest
*/
export function mergeDeep(dest, ...src) {
for (const s of src) {
dest = deepMerge_(dest, s);
}
return dest;
}
// recursively merges src into dest
function deepMerge_(dest, src) {
if (typeof src !== 'object' || src === null) {
return dest;
}
for (const p in src) {
if (!src.hasOwnProperty(p)) {
continue;
}
if (src[p] === undefined) {
continue;
}
if (typeof src[p] !== 'object' || isArray(src[p]) || src[p] === null) {
dest[p] = src[p];
}
else if (typeof dest[p] !== 'object' || dest[p] === null) {
dest[p] = mergeDeep(isArray(src[p].constructor) ? [] : {}, src[p]);
}
else {
mergeDeep(dest[p], src[p]);
}
}
return dest;
}
export function unique(values, f) {
const results = [];
const u = {};
let v;
for (const val of values) {
v = f(val);
if (v in u) {
continue;
}
u[v] = 1;
results.push(val);
}
return results;
}
/**
* Returns true if the two dictionaries disagree. Applies only to defined values.
*/
export function isEqual(dict, other) {
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(a, b) {
if (a.size !== b.size) {
return false;
}
for (const e of a) {
if (!b.has(e)) {
return false;
}
}
return true;
}
export function hasIntersection(a, b) {
for (const key of a) {
if (b.has(key)) {
return true;
}
}
return false;
}
export function prefixGenerator(a) {
const prefixes = new Set();
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(''));
computedPrefixes.forEach(y => prefixes.add(y));
}
return prefixes;
}
export function fieldIntersection(a, b) {
return hasIntersection(prefixGenerator(a), prefixGenerator(b));
}
export function isNumeric(num) {
return !isNaN(num);
}
export function differArray(array, other) {
if (array.length !== other.length) {
return true;
}
array.sort();
other.sort();
for (let i = 0; i < array.length; i++) {
if (other[i] !== array[i]) {
return true;
}
}
return false;
}
// 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;
export function vals(x) {
const _vals = [];
for (const k in x) {
if (x.hasOwnProperty(k)) {
_vals.push(x[k]);
}
}
return _vals;
}
export function entries(x) {
const _entries = [];
for (const k in x) {
if (x.hasOwnProperty(k)) {
_entries.push({
key: k,
value: x[k]
});
}
}
return _entries;
}
export function flagKeys(f) {
return keys(f);
}
export function isBoolean(b) {
return b === true || b === false;
}
/**
* Convert a string into a valid variable name
*/
export function varName(s) {
// 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(op, cb) {
if (isLogicalNot(op)) {
return '!(' + logicalExpr(op.not, cb) + ')';
}
else if (isLogicalAnd(op)) {
return '(' + op.and.map((and) => logicalExpr(and, cb)).join(') && (') + ')';
}
else if (isLogicalOr(op)) {
return '(' + op.or.map((or) => 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, orderedProps) {
if (orderedProps.length === 0) {
return true;
}
const prop = orderedProps.shift();
if (deleteNestedProperty(obj[prop], orderedProps)) {
delete obj[prop];
}
return keys(obj).length === 0;
}
export function titlecase(s) {
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, 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, datum = 'datum') {
return `${datum}[${stringValue(splitAccessPath(path).join('.'))}]`;
}
/**
* Replaces path accesses with access to non-nested field.
* For example, `foo["bar"].baz` becomes `foo\\.bar\\.baz`.
*/
export function replacePathInField(path) {
return `${splitAccessPath(path)
.map(p => p.replace('.', '\\.'))
.join('\\.')}`;
}
/**
* Remove path accesses with access from field.
* For example, `foo["bar"].baz` becomes `foo.bar.baz`.
*/
export function removePathFromField(path) {
return `${splitAccessPath(path).join('.')}`;
}
/**
* Count the depth of the path. Returns 1 for fields that are not nested.
*/
export function accessPathDepth(path) {
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(...args) {
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) {
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) {
return isInternalField(name) ? name : `__${name}`;
}
export function isInternalField(name) {
return name.indexOf('__') === 0;
}
/**
* Normalize angle to be within [0,360).
*/
export function normalizeAngle(angle) {
return ((angle % 360) + 360) % 360;
}
//# sourceMappingURL=util.js.map