-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdestructure.ts
63 lines (55 loc) · 1.7 KB
/
destructure.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
/*!
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project.
*/
import type { DestructureArgs } from '@datashaper/schema'
import { from, not } from 'arquero'
import { op } from 'arquero'
import type ColumnTable from 'arquero/dist/types/table/column-table.js'
import type { RowObject } from 'arquero/dist/types/table/table'
import type { ColumnTableStep } from './util/factories.js'
import { stepVerbFactory } from './util/factories.js'
export const destructureStep: ColumnTableStep<DestructureArgs> = (
input,
{ column, keys, preserveSource = false },
) => {
const tableArray: RowObject[] = input.objects()
for (let i = 0; i < tableArray.length; i++) {
if (tableArray[i] !== undefined && tableArray[i]?.[column] !== undefined) {
tableArray[i] = destructureSingleValue(
tableArray[i] ?? {},
tableArray[i]?.[column] ?? {},
keys,
)
}
}
const finalTable: ColumnTable = from(tableArray)
return preserveSource ? finalTable : finalTable.select(not(column))
}
function destructureSingleValue(
row: RowObject,
object: JSON,
keys?: string[],
): RowObject {
op.entries(object).forEach(function (entry) {
const [key, value] = entry
if (keys === undefined || keys.length === 0 || keys?.includes(key)) {
const val = isEmpty(value) ? null : value
row[key] = val
}
})
return row
}
export const destructure = stepVerbFactory(destructureStep)
function isEmpty(value: string | number | boolean | Date | null | undefined) {
if (value === null || value === undefined) {
return true
}
if (typeof value === 'number' && isNaN(value)) {
return true
}
if (typeof value === 'string' && value.length === 0) {
return true
}
return false
}