-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathutils.ts
114 lines (98 loc) · 2.62 KB
/
utils.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
import { Notation } from '@h5web/lib';
import {
isBoolType,
isComplexType,
isEnumType,
isIntegerType,
isNumericType,
} from '@h5web/shared/guards';
import {
type ComplexType,
type CompoundType,
DTypeClass,
type NumericType,
type PrintableType,
type ScalarValue,
} from '@h5web/shared/hdf5-models';
import { type ValueFormatter } from '@h5web/shared/vis-models';
import {
createComplexFormatter,
createEnumFormatter,
formatBool,
} from '@h5web/shared/vis-utils';
import { format } from 'd3-format';
export function createNumericFormatter(
notation: Notation,
): (val: number) => string {
switch (notation) {
case Notation.FixedPoint:
return format('.3f');
case Notation.Scientific:
return format('.3e');
default:
return format('.5~g');
}
}
export function createBigIntFormatter(
notation: Notation,
): (val: ScalarValue<NumericType>) => string {
switch (notation) {
case Notation.Scientific: {
const formatter = createNumericFormatter(notation);
return (val) => formatter(Number(val));
}
default:
return (val) => val.toString();
}
}
export function createMatrixComplexFormatter(
notation: Notation,
): (val: ScalarValue<ComplexType>) => string {
const formatStr =
notation === Notation.FixedPoint
? '.2f'
: `.3~${notation === Notation.Scientific ? 'e' : 'g'}`;
return createComplexFormatter(formatStr, true);
}
export function getFormatter(
type: PrintableType,
notation: Notation,
): (val: ScalarValue<PrintableType>) => string; // override distributivity of `ValueFormatter`
export function getFormatter(
type: PrintableType,
notation: Notation,
): ValueFormatter<PrintableType> {
if (isIntegerType(type) && type.size === 64) {
return createBigIntFormatter(notation);
}
if (isNumericType(type)) {
return createNumericFormatter(notation);
}
if (isBoolType(type)) {
return formatBool;
}
if (isEnumType(type)) {
return createEnumFormatter(type.mapping);
}
if (isComplexType(type)) {
return createMatrixComplexFormatter(notation);
}
return (val: string) => val.toString(); // call `toString()` for safety, in case type cast is wrong
}
export function getCellWidth(
type: PrintableType | CompoundType<PrintableType>,
): number {
if (type.class === DTypeClass.Compound) {
return Math.max(...Object.values(type.fields).map(getCellWidth));
}
if (type.class === DTypeClass.String) {
return type.length !== undefined ? 12 * type.length : 300;
}
if (type.class === DTypeClass.Bool) {
return 90;
}
if (type.class === DTypeClass.Complex) {
return 240;
}
return 120;
}