@kepler.gl/common-utils 3.3.0-alpha.2 → 3.3.0-alpha.21

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.
@@ -0,0 +1,606 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.ACCEPTED_ANALYZER_TYPES = void 0;
8
+ exports.analyzerTypeToFieldType = analyzerTypeToFieldType;
9
+ exports.getFieldsFromData = getFieldsFromData;
10
+ exports.getSampleForTypeAnalyze = getSampleForTypeAnalyze;
11
+ exports.getSampleForTypeAnalyzeArrow = getSampleForTypeAnalyzeArrow;
12
+ exports.renameDuplicateFields = renameDuplicateFields;
13
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
14
+ var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
15
+ var _typeAnalyzer = require("type-analyzer");
16
+ var _constants = require("@kepler.gl/constants");
17
+ var _window = require("global/window");
18
+ var _d3Array = require("d3-array");
19
+ var _data = require("./data");
20
+ var _h3Utils = require("./h3-utils");
21
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
22
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
23
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } // SPDX-License-Identifier: MIT
24
+ // Copyright contributors to the kepler.gl project
25
+ var H3_ANALYZER_TYPE = 'H3';
26
+
27
+ // a plain decimal number, optionally in scientific notation: 12, -0.5, .5, 1.5e+10, 2E-4
28
+ var DECIMAL_NUMBER_REGEX = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
29
+ var INTEGER_REGEX = /^[+-]?\d+$/;
30
+
31
+ /**
32
+ * type-analyzer reports NUMBER for values that pass `!isNaN` but match neither its INT nor
33
+ * its FLOAT regex, which in practice is mostly scientific notation such as `1.5e+10`. Such a
34
+ * value is safe to read as a real number unless it is a non decimal literal (`0x1A`, also hex
35
+ * hashes and addresses) or an integer beyond the safe range (64-bit ids), both of which
36
+ * parseFloat would misread or round.
37
+ */
38
+ function isRealNumberSample(value) {
39
+ if (!(0, _data.notNullorUndefined)(value) || value === '') {
40
+ return true;
41
+ }
42
+ if (typeof value === 'number') {
43
+ return Number.isFinite(value);
44
+ }
45
+ if (typeof value !== 'string' || !DECIMAL_NUMBER_REGEX.test(value)) {
46
+ return false;
47
+ }
48
+ var asNumber = Number(value);
49
+ return Number.isFinite(asNumber) && (!INTEGER_REGEX.test(value) || Number.isSafeInteger(asNumber));
50
+ }
51
+
52
+ /**
53
+ * type-analyzer uses `isNaN(value)`, which throws on BigInt
54
+ * ("Cannot convert a BigInt value to a number"). Arrow/Parquet Int64
55
+ * columns yield BigInt in JS, so stringify those samples first.
56
+ */
57
+ function toTypeAnalyzerValue(value) {
58
+ if (typeof value === 'string') {
59
+ return value.trim();
60
+ }
61
+ if (typeof value === 'bigint') {
62
+ return value.toString();
63
+ }
64
+ return value;
65
+ }
66
+ function isGeoJsonGeometry(value) {
67
+ var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
68
+ if (!value || (0, _typeof2["default"])(value) !== 'object' || depth > 32) return false;
69
+ var geometry = value;
70
+ if (geometry.type === 'Feature') return isGeoJsonGeometry(geometry.geometry, depth + 1);
71
+ if (geometry.type === 'GeometryCollection') {
72
+ return Array.isArray(geometry.geometries) && geometry.geometries.every(function (child) {
73
+ return isGeoJsonGeometry(child, depth + 1);
74
+ });
75
+ }
76
+ var position = function position(coordinates) {
77
+ return Array.isArray(coordinates) && coordinates.length >= 2 && coordinates.every(function (coordinate) {
78
+ return typeof coordinate === 'number' && Number.isFinite(coordinate);
79
+ });
80
+ };
81
+ var positions = function positions(coordinates, minimum) {
82
+ return Array.isArray(coordinates) && (coordinates.length === 0 || coordinates.length >= minimum) && coordinates.every(position);
83
+ };
84
+ var ring = function ring(coordinates) {
85
+ return positions(coordinates, 4) && (coordinates.length === 0 || coordinates[0].length === coordinates[coordinates.length - 1].length && coordinates[0].every(function (coordinate, index) {
86
+ return coordinate === coordinates[coordinates.length - 1][index];
87
+ }));
88
+ };
89
+ var polygon = function polygon(coordinates) {
90
+ return Array.isArray(coordinates) && coordinates.every(ring);
91
+ };
92
+ switch (geometry.type) {
93
+ case 'Point':
94
+ return position(geometry.coordinates);
95
+ case 'MultiPoint':
96
+ return positions(geometry.coordinates, 1);
97
+ case 'LineString':
98
+ return positions(geometry.coordinates, 2);
99
+ case 'MultiLineString':
100
+ return Array.isArray(geometry.coordinates) && geometry.coordinates.every(function (line) {
101
+ return positions(line, 2);
102
+ });
103
+ case 'Polygon':
104
+ return polygon(geometry.coordinates);
105
+ case 'MultiPolygon':
106
+ return Array.isArray(geometry.coordinates) && geometry.coordinates.every(polygon);
107
+ default:
108
+ return false;
109
+ }
110
+ }
111
+
112
+ /** Validate the complete WKT collection before changing a text column's type. */
113
+ function isWktGeometryCollection(value) {
114
+ var cursor = 0;
115
+ var consume = function consume(pattern) {
116
+ var _match$;
117
+ var match = pattern.exec(value.slice(cursor));
118
+ if (!match) return undefined;
119
+ cursor += match[0].length;
120
+ // Captures exclude leading whitespace; punctuation only needs a truthy result.
121
+ return (_match$ = match[1]) !== null && _match$ !== void 0 ? _match$ : match[0];
122
+ };
123
+ var number = DECIMAL_NUMBER_REGEX.source.slice(1, -1);
124
+ var positionPattern = new RegExp("^\\s*(".concat(number, ")\\s+(").concat(number, ")((?:\\s+").concat(number, ")*)"), 'i');
125
+ var group = function group(read) {
126
+ if (!consume(/^\s*\(/)) return null;
127
+ var items = [];
128
+ do {
129
+ var item = read();
130
+ if (item == null) return null;
131
+ items.push(item);
132
+ } while (consume(/^\s*,/));
133
+ return consume(/^\s*\)/) ? items : null;
134
+ };
135
+ var _readGeometry = function readGeometry(depth, inheritedDimensions) {
136
+ var _consume, _consume2;
137
+ if (depth > 32) return null;
138
+ var type = (_consume = consume(/^\s*(GEOMETRYCOLLECTION|MULTIPOLYGON|MULTILINESTRING|MULTIPOINT|POLYGON|LINESTRING|POINT)\b/i)) === null || _consume === void 0 ? void 0 : _consume.toUpperCase();
139
+ if (!type) return null;
140
+ var dimension = (_consume2 = consume(/^\s+(ZM|Z|M)\b/i)) === null || _consume2 === void 0 ? void 0 : _consume2.toUpperCase();
141
+ var dimensions = dimension ? dimension === 'ZM' ? 4 : 3 : inheritedDimensions;
142
+ if (consume(/^\s*EMPTY\b/i)) return {};
143
+ if (type === 'GEOMETRYCOLLECTION') {
144
+ return group(function () {
145
+ return _readGeometry(depth + 1, dimensions);
146
+ });
147
+ }
148
+ var _readCoordinates = function readCoordinates(level) {
149
+ if (level > 3) return null;
150
+ if (/^\s*\(/.test(value.slice(cursor))) return group(function () {
151
+ return _readCoordinates(level + 1);
152
+ });
153
+ var match = positionPattern.exec(value.slice(cursor));
154
+ if (!match) return null;
155
+ cursor += match[0].length;
156
+ // Capture common XY positions directly, without splitting/trimming each tuple.
157
+ var coordinates = [+match[1], +match[2]];
158
+ var _iterator = _createForOfIteratorHelper(match[3].match(/\S+/g) || []),
159
+ _step;
160
+ try {
161
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
162
+ var coordinate = _step.value;
163
+ coordinates.push(+coordinate);
164
+ }
165
+ } catch (err) {
166
+ _iterator.e(err);
167
+ } finally {
168
+ _iterator.f();
169
+ }
170
+ return coordinates.every(Number.isFinite) && (!dimensions || coordinates.length === dimensions) ? coordinates : null;
171
+ };
172
+ var coordinates = group(function () {
173
+ return _readCoordinates(0);
174
+ });
175
+ if (!coordinates) return null;
176
+ if (type === 'POINT') {
177
+ if (coordinates.length !== 1) return null;
178
+ coordinates = coordinates[0];
179
+ } else if (type === 'MULTIPOINT' && coordinates.every(function (point) {
180
+ return Array.isArray(point) && point.length === 1;
181
+ })) {
182
+ coordinates = coordinates.map(function (point) {
183
+ return point[0];
184
+ });
185
+ }
186
+ var types = {
187
+ POINT: 'Point',
188
+ MULTIPOINT: 'MultiPoint',
189
+ LINESTRING: 'LineString',
190
+ MULTILINESTRING: 'MultiLineString',
191
+ POLYGON: 'Polygon',
192
+ MULTIPOLYGON: 'MultiPolygon'
193
+ };
194
+ return isGeoJsonGeometry({
195
+ type: types[type],
196
+ coordinates: coordinates
197
+ }) ? {} : null;
198
+ };
199
+ return _readGeometry(0) != null && value.slice(cursor).trim() === '';
200
+ }
201
+ function isAdditionalGeometry(value) {
202
+ if (typeof value !== 'string') return isGeoJsonGeometry(value);
203
+ if (/^GEOMETRYCOLLECTION\b/i.test(value)) return isWktGeometryCollection(value);
204
+ if (!value.startsWith('{')) return false;
205
+ try {
206
+ return isGeoJsonGeometry(JSON.parse(value));
207
+ } catch (_unused) {
208
+ return false;
209
+ }
210
+ }
211
+
212
+ /** Validate numeric-looking WKB before overriding NUMBER (e.g. account IDs). */
213
+ function isCompleteWkb(value) {
214
+ if (typeof value !== 'string' || !(0, _data.isHexWkb)(value)) return false;
215
+ var length = value.length / 2;
216
+ var uint32 = function uint32(offset, littleEndian) {
217
+ if (offset + 4 > length) throw new Error('Truncated WKB');
218
+ var number = 0;
219
+ for (var i = 0; i < 4; i++) {
220
+ var _byte = parseInt(value.slice((offset + i) * 2, (offset + i + 1) * 2), 16);
221
+ number += _byte * Math.pow(256, littleEndian ? i : 3 - i);
222
+ }
223
+ return number;
224
+ };
225
+ var _endOfGeometry = function endOfGeometry(offset, depth) {
226
+ if (depth > 32 || offset + 5 > length) throw new Error('Invalid WKB');
227
+ var order = value.slice(offset * 2, offset * 2 + 2);
228
+ if (order !== '00' && order !== '01') throw new Error('Invalid WKB byte order');
229
+ var littleEndian = order === '01';
230
+ var rawType = uint32(offset + 1, littleEndian);
231
+ var type = rawType & 0x1fffffff;
232
+ var dimensions = 2 + Number(Boolean(rawType & 0x80000000) || [1, 3].includes(Math.floor(type / 1000))) + Number(Boolean(rawType & 0x40000000) || [2, 3].includes(Math.floor(type / 1000)));
233
+ var baseType = type % 1000;
234
+ if (baseType < 1 || baseType > 7 || type >= 4000) throw new Error('Invalid WKB type');
235
+ var cursor = offset + 5 + (rawType & 0x20000000 ? 4 : 0);
236
+ if (baseType === 1) return cursor + dimensions * 8;
237
+ var count = uint32(cursor, littleEndian);
238
+ cursor += 4;
239
+ if (baseType === 2) return cursor + count * dimensions * 8;
240
+ if (count > (length - cursor) / (baseType === 3 ? 4 : 5)) throw new Error('Truncated WKB');
241
+ for (var i = 0; i < count; i++) {
242
+ if (baseType === 3) {
243
+ var points = uint32(cursor, littleEndian);
244
+ cursor += 4 + points * dimensions * 8;
245
+ } else {
246
+ cursor = _endOfGeometry(cursor, depth + 1);
247
+ }
248
+ if (cursor > length) throw new Error('Truncated WKB');
249
+ }
250
+ return cursor;
251
+ };
252
+ try {
253
+ return _endOfGeometry(0, 0) === length;
254
+ } catch (_unused2) {
255
+ return false;
256
+ }
257
+ }
258
+ var ACCEPTED_ANALYZER_TYPES = exports.ACCEPTED_ANALYZER_TYPES = [_typeAnalyzer.DATA_TYPES.DATE, _typeAnalyzer.DATA_TYPES.TIME, _typeAnalyzer.DATA_TYPES.DATETIME, _typeAnalyzer.DATA_TYPES.NUMBER, _typeAnalyzer.DATA_TYPES.INT, _typeAnalyzer.DATA_TYPES.FLOAT, _typeAnalyzer.DATA_TYPES.BOOLEAN, _typeAnalyzer.DATA_TYPES.STRING, _typeAnalyzer.DATA_TYPES.GEOMETRY, _typeAnalyzer.DATA_TYPES.GEOMETRY_FROM_STRING, _typeAnalyzer.DATA_TYPES.PAIR_GEOMETRY_FROM_STRING, _typeAnalyzer.DATA_TYPES.ZIPCODE, _typeAnalyzer.DATA_TYPES.ARRAY, _typeAnalyzer.DATA_TYPES.OBJECT, H3_ANALYZER_TYPE];
259
+ var IGNORE_DATA_TYPES = Object.keys(_typeAnalyzer.DATA_TYPES).filter(function (type) {
260
+ return !ACCEPTED_ANALYZER_TYPES.includes(type);
261
+ });
262
+
263
+ /**
264
+ * Getting sample data for analyzing field type.
265
+ */
266
+ function getSampleForTypeAnalyze(_ref) {
267
+ var fields = _ref.fields,
268
+ rows = _ref.rows,
269
+ _ref$sampleCount = _ref.sampleCount,
270
+ sampleCount = _ref$sampleCount === void 0 ? 50 : _ref$sampleCount;
271
+ var total = Math.min(sampleCount, rows.length);
272
+ // const fieldOrder = fields.map(f => f.name);
273
+ var sample = (0, _d3Array.range)(0, total, 1).map(function () {
274
+ return {};
275
+ });
276
+ if (rows.length < 1) {
277
+ return [];
278
+ }
279
+ var isRowObject = !Array.isArray(rows[0]);
280
+
281
+ // collect sample data for each field
282
+ fields.forEach(function (field, fieldIdx) {
283
+ // row counter
284
+ var i = 0;
285
+ // sample counter
286
+ var j = 0;
287
+ while (j < total) {
288
+ if (i >= rows.length) {
289
+ // if depleted data pool
290
+ sample[j][field] = null;
291
+ j++;
292
+ } else if ((0, _data.notNullorUndefined)(rows[i][isRowObject ? field : fieldIdx])) {
293
+ var value = rows[i][isRowObject ? field : fieldIdx];
294
+ sample[j][field] = toTypeAnalyzerValue(value);
295
+ j++;
296
+ i++;
297
+ } else {
298
+ i++;
299
+ }
300
+ }
301
+ });
302
+ return sample;
303
+ }
304
+
305
+ /**
306
+ * Getting sample data for analyzing field type for Arrow tables.
307
+ * @param table Arrow table or an array of vectors.
308
+ * @param fields Field names.
309
+ * @param sampleCount Number of sample rows to get.
310
+ * @returns Sample rows.
311
+ */
312
+ function getSampleForTypeAnalyzeArrow(table, fields) {
313
+ var sampleCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
314
+ var isTable = !Array.isArray(table);
315
+ var numRows = isTable ? table.numRows : table[0].length;
316
+ var getVector = isTable ? function (index) {
317
+ return table.getChildAt(index);
318
+ } : function (index) {
319
+ return table[index];
320
+ };
321
+ var total = Math.min(sampleCount, numRows);
322
+ var sample = (0, _d3Array.range)(0, total, 1).map(function () {
323
+ return {};
324
+ });
325
+ if (numRows < 1) {
326
+ return [];
327
+ }
328
+
329
+ // collect sample data for each field
330
+ fields.forEach(function (field, fieldIdx) {
331
+ var rowIndex = 0;
332
+ var sampleIndex = 0;
333
+ while (sampleIndex < total) {
334
+ var _getVector;
335
+ if (rowIndex >= numRows) {
336
+ // if depleted data pool
337
+ sample[sampleIndex][field] = null;
338
+ sampleIndex++;
339
+ } else if ((0, _data.notNullorUndefined)((_getVector = getVector(fieldIdx)) === null || _getVector === void 0 ? void 0 : _getVector.get(rowIndex))) {
340
+ var _getVector2;
341
+ var value = (_getVector2 = getVector(fieldIdx)) === null || _getVector2 === void 0 ? void 0 : _getVector2.get(rowIndex);
342
+ sample[sampleIndex][field] = toTypeAnalyzerValue(value);
343
+ sampleIndex++;
344
+ rowIndex++;
345
+ } else {
346
+ rowIndex++;
347
+ }
348
+ }
349
+ });
350
+ return sample;
351
+ }
352
+
353
+ /**
354
+ * Convert type-analyzer output to kepler.gl field types
355
+ *
356
+ * @param aType
357
+ * @returns corresponding type in `ALL_FIELD_TYPES`
358
+ */
359
+ /* eslint-disable complexity */
360
+ function analyzerTypeToFieldType(aType) {
361
+ var DATE = _typeAnalyzer.DATA_TYPES.DATE,
362
+ TIME = _typeAnalyzer.DATA_TYPES.TIME,
363
+ DATETIME = _typeAnalyzer.DATA_TYPES.DATETIME,
364
+ NUMBER = _typeAnalyzer.DATA_TYPES.NUMBER,
365
+ INT = _typeAnalyzer.DATA_TYPES.INT,
366
+ FLOAT = _typeAnalyzer.DATA_TYPES.FLOAT,
367
+ BOOLEAN = _typeAnalyzer.DATA_TYPES.BOOLEAN,
368
+ STRING = _typeAnalyzer.DATA_TYPES.STRING,
369
+ GEOMETRY = _typeAnalyzer.DATA_TYPES.GEOMETRY,
370
+ GEOMETRY_FROM_STRING = _typeAnalyzer.DATA_TYPES.GEOMETRY_FROM_STRING,
371
+ PAIR_GEOMETRY_FROM_STRING = _typeAnalyzer.DATA_TYPES.PAIR_GEOMETRY_FROM_STRING,
372
+ ZIPCODE = _typeAnalyzer.DATA_TYPES.ZIPCODE,
373
+ ARRAY = _typeAnalyzer.DATA_TYPES.ARRAY,
374
+ OBJECT = _typeAnalyzer.DATA_TYPES.OBJECT;
375
+
376
+ // TODO: un recognized types
377
+ // CURRENCY PERCENT NONE
378
+ switch (aType) {
379
+ case DATE:
380
+ return _constants.ALL_FIELD_TYPES.date;
381
+ case TIME:
382
+ case DATETIME:
383
+ return _constants.ALL_FIELD_TYPES.timestamp;
384
+ case FLOAT:
385
+ return _constants.ALL_FIELD_TYPES.real;
386
+ case INT:
387
+ return _constants.ALL_FIELD_TYPES.integer;
388
+ case BOOLEAN:
389
+ return _constants.ALL_FIELD_TYPES["boolean"];
390
+ case GEOMETRY:
391
+ case GEOMETRY_FROM_STRING:
392
+ case PAIR_GEOMETRY_FROM_STRING:
393
+ return _constants.ALL_FIELD_TYPES.geojson;
394
+ case ARRAY:
395
+ return _constants.ALL_FIELD_TYPES.array;
396
+ case OBJECT:
397
+ return _constants.ALL_FIELD_TYPES.object;
398
+ case NUMBER:
399
+ case STRING:
400
+ case ZIPCODE:
401
+ return _constants.ALL_FIELD_TYPES.string;
402
+ case H3_ANALYZER_TYPE:
403
+ return _constants.ALL_FIELD_TYPES.h3;
404
+ default:
405
+ _window.console.warn("Unsupported analyzer type: ".concat(aType));
406
+ return _constants.ALL_FIELD_TYPES.string;
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Analyze field types from data in `string` format, e.g. uploaded csv.
412
+ * Assign `type`, `fieldIdx` and `format` (timestamp only) to each field
413
+ *
414
+ * @param data array of row object
415
+ * @param fieldOrder array of field names as string
416
+ * @returns formatted fields
417
+ * @public
418
+ * @example
419
+ *
420
+ * import {getFieldsFromData} from '@kepler.gl/common-utils';
421
+ * const data = [{
422
+ * time: '2016-09-17 00:09:55',
423
+ * value: '4',
424
+ * surge: '1.2',
425
+ * isTrip: 'true',
426
+ * zeroOnes: '0'
427
+ * }, {
428
+ * time: '2016-09-17 00:30:08',
429
+ * value: '3',
430
+ * surge: null,
431
+ * isTrip: 'false',
432
+ * zeroOnes: '1'
433
+ * }, {
434
+ * time: null,
435
+ * value: '2',
436
+ * surge: '1.3',
437
+ * isTrip: null,
438
+ * zeroOnes: '1'
439
+ * }];
440
+ *
441
+ * const fieldOrder = ['time', 'value', 'surge', 'isTrip', 'zeroOnes'];
442
+ * const fields = getFieldsFromData(data, fieldOrder);
443
+ * // fields = [
444
+ * // {name: 'time', format: 'YYYY-M-D H:m:s', fieldIdx: 1, type: 'timestamp'},
445
+ * // {name: 'value', format: '', fieldIdx: 4, type: 'integer'},
446
+ * // {name: 'surge', format: '', fieldIdx: 5, type: 'real'},
447
+ * // {name: 'isTrip', format: '', fieldIdx: 6, type: 'boolean'},
448
+ * // {name: 'zeroOnes', format: '', fieldIdx: 7, type: 'integer'}];
449
+ *
450
+ */
451
+ function getFieldsFromData(data, fieldOrder) {
452
+ // add a check for epoch timestamp
453
+ var analyzerData = data.map(function (row) {
454
+ var next = {};
455
+ var _iterator2 = _createForOfIteratorHelper(fieldOrder),
456
+ _step2;
457
+ try {
458
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
459
+ var key = _step2.value;
460
+ next[key] = toTypeAnalyzerValue(row[key]);
461
+ }
462
+ } catch (err) {
463
+ _iterator2.e(err);
464
+ } finally {
465
+ _iterator2.f();
466
+ }
467
+ return next;
468
+ });
469
+ var metadata = _typeAnalyzer.Analyzer.computeColMeta(analyzerData, [{
470
+ regex: /.*geojson|all_points/g,
471
+ dataType: 'GEOMETRY'
472
+ }, {
473
+ regex: /.*census/g,
474
+ dataType: 'STRING'
475
+ }], {
476
+ ignoredDataTypes: IGNORE_DATA_TYPES
477
+ });
478
+ var _renameDuplicateField = renameDuplicateFields(fieldOrder),
479
+ fieldByIndex = _renameDuplicateField.fieldByIndex;
480
+ var result = fieldOrder.map(function (field, index) {
481
+ var name = fieldByIndex[index];
482
+ var fieldMeta = metadata.find(function (m) {
483
+ return m.key === field;
484
+ });
485
+
486
+ // fieldMeta could be undefined if the field has no data and Analyzer.computeColMeta
487
+ // will ignore the field. In this case, we will simply assign the field type to STRING
488
+ // since dropping the column in the RowData could be expensive
489
+ var type = (fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.type) || 'STRING';
490
+ var format = (fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.format) || '';
491
+
492
+ // type-analyzer's unanchored year-first regex matches a prefix of slash dates
493
+ // (e.g. 09/17/20 in 09/17/2016). Correct only complete date samples. Keep the
494
+ // month-first default unless every sample is a valid day-first date and at
495
+ // least one day exceeds 12; ambiguous or conflicting samples cannot decide.
496
+ if (type === _typeAnalyzer.DATA_TYPES.DATE && ['YYYY/M/D', 'M/D/YYYY'].includes(format)) {
497
+ var samples = analyzerData.map(function (row) {
498
+ return row[field];
499
+ }).filter(_data.notNullorUndefined);
500
+ if (samples.length && samples.every(function (value) {
501
+ return typeof value === 'string' && /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(value);
502
+ })) {
503
+ var hasDayFirstEvidence = false;
504
+ var allDayFirst = samples.every(function (value) {
505
+ var _String$split$map = String(value).split('/').map(Number),
506
+ _String$split$map2 = (0, _slicedToArray2["default"])(_String$split$map, 3),
507
+ day = _String$split$map2[0],
508
+ month = _String$split$map2[1],
509
+ year = _String$split$map2[2];
510
+ var date = new Date(0);
511
+ date.setUTCFullYear(year, month - 1, day);
512
+ hasDayFirstEvidence || (hasDayFirstEvidence = day > 12);
513
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
514
+ });
515
+ format = allDayFirst && hasDayFirstEvidence ? 'D/M/YYYY' : 'M/D/YYYY';
516
+ }
517
+ }
518
+
519
+ // quick check if first valid string in column is H3
520
+ if (type === _typeAnalyzer.DATA_TYPES.STRING) {
521
+ for (var i = 0, n = analyzerData.length; i < n; ++i) {
522
+ var sampleValue = analyzerData[i][name];
523
+ if (typeof sampleValue === 'string') {
524
+ type = (0, _h3Utils.h3IsValid)(sampleValue) ? H3_ANALYZER_TYPE : type;
525
+ break;
526
+ }
527
+ if ((0, _data.notNullorUndefined)(sampleValue)) {
528
+ break;
529
+ }
530
+ }
531
+ }
532
+
533
+ // quick check if string is hex wkb
534
+ if (type === _typeAnalyzer.DATA_TYPES.STRING) {
535
+ type = data.some(function (d) {
536
+ return (0, _data.isHexWkb)(d[name]);
537
+ }) ? _typeAnalyzer.DATA_TYPES.GEOMETRY : type;
538
+ }
539
+
540
+ // The analyzer treats numeric-only WKB as NUMBER and GeoJSON strings as
541
+ // OBJECT. Only override these fallback types when every present sample
542
+ // describes geometry; unrelated objects, text and identifiers stay intact.
543
+ if ([_typeAnalyzer.DATA_TYPES.STRING, _typeAnalyzer.DATA_TYPES.NUMBER, _typeAnalyzer.DATA_TYPES.OBJECT].includes(type)) {
544
+ var _samples = analyzerData.map(function (row) {
545
+ return row[field];
546
+ }).filter(_data.notNullorUndefined);
547
+ if (_samples.length && _samples.every(function (value) {
548
+ return isAdditionalGeometry(value) || type === _typeAnalyzer.DATA_TYPES.NUMBER && isCompleteWkb(value);
549
+ })) {
550
+ type = _typeAnalyzer.DATA_TYPES.GEOMETRY;
551
+ }
552
+ }
553
+
554
+ // read a column of numbers in scientific notation as real numbers instead of strings
555
+ if (type === _typeAnalyzer.DATA_TYPES.NUMBER && analyzerData.every(function (row) {
556
+ return isRealNumberSample(row[field]);
557
+ })) {
558
+ type = _typeAnalyzer.DATA_TYPES.FLOAT;
559
+ }
560
+ return {
561
+ name: name,
562
+ id: name,
563
+ displayName: name,
564
+ format: format,
565
+ fieldIdx: index,
566
+ type: analyzerTypeToFieldType(type),
567
+ analyzerType: type,
568
+ valueAccessor: function valueAccessor(dc) {
569
+ return function (d) {
570
+ return dc.valueAt(d.index, index);
571
+ };
572
+ }
573
+ };
574
+ });
575
+ return result;
576
+ }
577
+
578
+ /**
579
+ * pass in an array of field names, rename duplicated one
580
+ * and return a map from old field index to new name
581
+ *
582
+ * @param fieldOrder
583
+ * @returns new field name by index
584
+ */
585
+ function renameDuplicateFields(fieldOrder) {
586
+ return fieldOrder.reduce(function (accu, field, i) {
587
+ var allNames = accu.allNames;
588
+ var fieldName = field;
589
+
590
+ // add a counter to duplicated names
591
+ if (allNames.includes(field)) {
592
+ var counter = 0;
593
+ while (allNames.includes("".concat(field, "-").concat(counter))) {
594
+ counter++;
595
+ }
596
+ fieldName = "".concat(field, "-").concat(counter);
597
+ }
598
+ accu.fieldByIndex[i] = fieldName;
599
+ accu.allNames.push(fieldName);
600
+ return accu;
601
+ }, {
602
+ allNames: [],
603
+ fieldByIndex: []
604
+ });
605
+ }
606
+ //# sourceMappingURL=data-type.js.map