markdown-up 1.7.5 → 1.8.0
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.
- package/README.md +62 -7
- package/lib/app.js +4 -35
- package/lib/data.js +347 -340
- package/lib/dataTable.js +93 -41
- package/lib/lineChart.js +192 -129
- package/lib/script.js +39 -329
- package/lib/scriptLibrary.js +377 -62
- package/package.json +4 -4
- package/lib/barChart.js +0 -36
- package/lib/csv.js +0 -68
- package/lib/model.js +0 -292
- package/lib/util.js +0 -176
package/lib/data.js
CHANGED
|
@@ -3,224 +3,70 @@
|
|
|
3
3
|
|
|
4
4
|
/** @module lib/data */
|
|
5
5
|
|
|
6
|
-
import {parseCSV, parseCSVDatetime, parseCSVNumber} from './csv.js';
|
|
7
|
-
import {compareValues} from './util.js';
|
|
8
|
-
import {escapeMarkdownText} from 'markdown-model/lib/elements.js';
|
|
9
6
|
import {evaluateExpression} from 'calc-script/lib/runtime.js';
|
|
10
7
|
import {parseExpression} from 'calc-script/lib/parser.js';
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
/* c8 ignore start */
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
// Data expression functions
|
|
17
|
-
const dataExprFunctions = {
|
|
18
|
-
'markdownEscape': ([text]) => escapeMarkdownText(text)
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
// Helper function to create the data expression's variables argument
|
|
23
|
-
function createDataVariables(chart, variables = null) {
|
|
24
|
-
const dataVariables = {...dataExprFunctions};
|
|
25
|
-
const evalOptions = {'globals': dataVariables};
|
|
26
|
-
|
|
27
|
-
// Add the chart model variable expressions
|
|
28
|
-
if (chart !== null && 'var' in chart) {
|
|
29
|
-
for (const varName of Object.keys(chart.var)) {
|
|
30
|
-
const varExpr = parseExpression(chart.var[varName]);
|
|
31
|
-
dataVariables[varName] = evaluateExpression(varExpr, evalOptions);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// Add the options variables
|
|
36
|
-
if (variables !== null) {
|
|
37
|
-
Object.assign(dataVariables, variables);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return dataVariables;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* The loadChartData result object
|
|
46
|
-
*
|
|
47
|
-
* @typedef {Object} LoadChartDataResult
|
|
48
|
-
* @property {Object[]} data - The data row object array
|
|
49
|
-
* @property {Object} types - The map of field name to field type ("datetime", "number", "string")
|
|
50
|
-
* @property {Object} variables - The map of computed variable expression values
|
|
51
|
-
*/
|
|
8
|
+
import {parseSchemaMarkdown} from 'schema-markdown/lib/parser.js';
|
|
9
|
+
import {validateType} from 'schema-markdown/lib/schema.js';
|
|
52
10
|
|
|
53
11
|
|
|
54
12
|
/**
|
|
55
|
-
*
|
|
13
|
+
* Parse and validate CSV text to a data array
|
|
56
14
|
*
|
|
57
|
-
* @
|
|
58
|
-
* @
|
|
59
|
-
* @param {Object} [options=null] - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
|
|
60
|
-
* @returns [LoadChartDataResult]{@link module:lib/data~LoadChartDataResult}
|
|
15
|
+
* @param {string} text - The CSV text
|
|
16
|
+
* @returns {Object[]} The data array
|
|
61
17
|
*/
|
|
62
|
-
export
|
|
63
|
-
//
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if ('calc' in chart) {
|
|
71
|
-
for (const calculatedField of chart.calc) {
|
|
72
|
-
types[calculatedField.name] = addCalculatedField(data, calculatedField.name, calculatedField.expr, variables);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// Filter the data
|
|
77
|
-
if ('filter' in chart) {
|
|
78
|
-
data = filterData(data, chart.filter, variables);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// Aggregate the data
|
|
82
|
-
if ('agg' in chart) {
|
|
83
|
-
({data, types} = aggregateData(chart.agg, data, types));
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Add the post-aggregation calculated fields
|
|
87
|
-
if ('aggcalc' in chart) {
|
|
88
|
-
for (const calculatedField of chart.aggcalc) {
|
|
89
|
-
types[calculatedField.name] = addCalculatedField(data, calculatedField.name, calculatedField.expr, variables);
|
|
18
|
+
export function parseCSV(text) {
|
|
19
|
+
// Line-split the text
|
|
20
|
+
const lines = [];
|
|
21
|
+
if (typeof text === 'string') {
|
|
22
|
+
lines.push(...text.split(rCSVLineSplit));
|
|
23
|
+
} else {
|
|
24
|
+
for (const textPart of text) {
|
|
25
|
+
lines.push(...textPart.split(rCSVLineSplit));
|
|
90
26
|
}
|
|
91
27
|
}
|
|
92
28
|
|
|
93
|
-
//
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* The loadData result object
|
|
109
|
-
*
|
|
110
|
-
* @typedef {Object} LoadDataResult
|
|
111
|
-
* @property {Object[]} data - The data row object array
|
|
112
|
-
* @property {Object} types - The map of field name to field type ("datetime", "number", "string")
|
|
113
|
-
*/
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Load a data model
|
|
118
|
-
*
|
|
119
|
-
* @async
|
|
120
|
-
* @param {Object} dataModel - The data model
|
|
121
|
-
* @param {Object} options - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
|
|
122
|
-
* @returns [LoadDataResult]{@link module:lib/data~LoadDataResult}
|
|
123
|
-
*/
|
|
124
|
-
export async function loadData(dataModel, options) {
|
|
125
|
-
const dataBases = [dataModel, ...('join' in dataModel ? dataModel.join : [])];
|
|
126
|
-
const dataURLs = dataBases.map((base) => base.url);
|
|
127
|
-
const dataResponses = await Promise.all(dataURLs.map((joinURL) => options.fetchFn(options.urlFn(joinURL))));
|
|
128
|
-
const dataTypes = await Promise.all(dataResponses.map((response, ixResponse) => dataResponseHandler(dataURLs[ixResponse], response)));
|
|
129
|
-
|
|
130
|
-
// Compute the data variable values
|
|
131
|
-
const dataVariables = options.variables ?? createDataVariables(null);
|
|
132
|
-
const evalOptions = {'globals': dataVariables};
|
|
133
|
-
|
|
134
|
-
// Join the data
|
|
135
|
-
let [{data}] = dataTypes;
|
|
136
|
-
const [{types}] = dataTypes;
|
|
137
|
-
if ('join' in dataModel) {
|
|
138
|
-
// Helper function to compute a unique field name
|
|
139
|
-
const mapFieldName = (field) => {
|
|
140
|
-
let unique = field;
|
|
141
|
-
let ixUnique = 2;
|
|
142
|
-
while (unique in types) {
|
|
143
|
-
unique = `${field}${ixUnique}`;
|
|
144
|
-
ixUnique += 1;
|
|
145
|
-
}
|
|
146
|
-
return [field, unique];
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
// Perform each join in sequence
|
|
150
|
-
let leftData;
|
|
151
|
-
for (let ixJoin = 0; ixJoin < dataModel.join.length; ixJoin++) {
|
|
152
|
-
const join = dataModel.join[ixJoin];
|
|
153
|
-
const {'leftJoin': isLeftJoin = false} = join;
|
|
154
|
-
const leftExpression = parseExpression(join.left);
|
|
155
|
-
const rightExpression = parseExpression('right' in join ? join.right : join.left);
|
|
156
|
-
const rightData = dataTypes[ixJoin + 1].data;
|
|
157
|
-
const rightTypes = dataTypes[ixJoin + 1].types;
|
|
158
|
-
|
|
159
|
-
// Bucket the right rows by the right expression value
|
|
160
|
-
const rightCategoryRows = {};
|
|
161
|
-
for (const row of rightData) {
|
|
162
|
-
const categoryKey = JSON.stringify(evaluateExpression(rightExpression, evalOptions, row));
|
|
163
|
-
if (!(categoryKey in rightCategoryRows)) {
|
|
164
|
-
rightCategoryRows[categoryKey] = [];
|
|
165
|
-
}
|
|
166
|
-
rightCategoryRows[categoryKey].push(row);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// Compute the right column names
|
|
170
|
-
const rightFieldMap = Object.fromEntries(Object.keys(rightTypes).map(mapFieldName));
|
|
171
|
-
for (const rightField of Object.keys(rightTypes)) {
|
|
172
|
-
types[rightFieldMap[rightField]] = rightTypes[rightField];
|
|
29
|
+
// Split lines into rows
|
|
30
|
+
const rows = lines.filter((line) => !line.match(rCSVBlankLine)).map((line) => {
|
|
31
|
+
const row = [];
|
|
32
|
+
let linePart = line;
|
|
33
|
+
while (linePart !== '') {
|
|
34
|
+
// Quoted field?
|
|
35
|
+
const mQuoted = linePart.match(rCSVQuotedField) ?? linePart.match(rCSVQuotedFieldEnd);
|
|
36
|
+
if (mQuoted !== null) {
|
|
37
|
+
row.push(mQuoted[1].replaceAll(rCSVQuoteEscape, '"'));
|
|
38
|
+
linePart = linePart.slice(mQuoted[0].length);
|
|
39
|
+
continue;
|
|
173
40
|
}
|
|
174
41
|
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
data.push(row);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
42
|
+
// Non-quoted field
|
|
43
|
+
const ixComma = linePart.indexOf(',');
|
|
44
|
+
row.push(ixComma !== -1 ? linePart.slice(0, ixComma) : linePart);
|
|
45
|
+
linePart = (ixComma !== -1 ? linePart.slice(ixComma + 1) : '');
|
|
46
|
+
}
|
|
47
|
+
return row;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Assemble the data rows
|
|
51
|
+
const result = [];
|
|
52
|
+
if (rows.length >= 2) {
|
|
53
|
+
const [fields] = rows;
|
|
54
|
+
for (let ixLine = 1; ixLine < rows.length; ixLine += 1) {
|
|
55
|
+
const row = rows[ixLine];
|
|
56
|
+
result.push(Object.fromEntries(fields.map(
|
|
57
|
+
(field, ixField) => [field, ixField < row.length ? row[ixField] : 'null']
|
|
58
|
+
)));
|
|
195
59
|
}
|
|
196
60
|
}
|
|
197
61
|
|
|
198
|
-
return
|
|
62
|
+
return result;
|
|
199
63
|
}
|
|
200
64
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const status = response.statusText;
|
|
207
|
-
throw new Error(`Could not fetch "${url}"${status === '' ? '' : `, ${JSON.stringify(status)}`}`);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// CSV?
|
|
211
|
-
let data;
|
|
212
|
-
const csv = url.endsWith('.csv');
|
|
213
|
-
if (csv) {
|
|
214
|
-
data = parseCSV(await response.text());
|
|
215
|
-
} else {
|
|
216
|
-
data = await response.json();
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// Validate the data
|
|
220
|
-
const types = validateData(data, csv);
|
|
221
|
-
|
|
222
|
-
return {data, types};
|
|
223
|
-
}
|
|
65
|
+
const rCSVLineSplit = /\r?\n/;
|
|
66
|
+
const rCSVBlankLine = /^\s*$/;
|
|
67
|
+
const rCSVQuotedField = /^"((?:""|[^"])*)",/;
|
|
68
|
+
const rCSVQuotedFieldEnd = /^"((?:""|[^"])*)"\s*$/;
|
|
69
|
+
const rCSVQuoteEscape = /""/g;
|
|
224
70
|
|
|
225
71
|
|
|
226
72
|
/**
|
|
@@ -229,6 +75,7 @@ async function dataResponseHandler(url, response) {
|
|
|
229
75
|
* @param {Object[]} data - The data array. Row objects are updated with parsed/validated values.
|
|
230
76
|
* @param {boolean} [csv=false] - If true, parse number and null strings
|
|
231
77
|
* @returns {Object} The map of field name to field type ("datetime", "number", "string")
|
|
78
|
+
* @throws Throws an error if data is invalid
|
|
232
79
|
*/
|
|
233
80
|
export function validateData(data, csv = false) {
|
|
234
81
|
// Determine field types
|
|
@@ -241,9 +88,9 @@ export function validateData(data, csv = false) {
|
|
|
241
88
|
} else if (value instanceof Date) {
|
|
242
89
|
types[field] = 'datetime';
|
|
243
90
|
} else if (typeof value === 'string' && (!csv || value !== 'null')) {
|
|
244
|
-
if (
|
|
91
|
+
if (parseDatetime(value) !== null) {
|
|
245
92
|
types[field] = 'datetime';
|
|
246
|
-
} else if (csv &&
|
|
93
|
+
} else if (csv && parseNumber(value) !== null) {
|
|
247
94
|
types[field] = 'number';
|
|
248
95
|
} else {
|
|
249
96
|
types[field] = 'string';
|
|
@@ -259,7 +106,7 @@ export function validateData(data, csv = false) {
|
|
|
259
106
|
};
|
|
260
107
|
for (const row of data) {
|
|
261
108
|
for (const [field, value] of Object.entries(row)) {
|
|
262
|
-
const fieldType =
|
|
109
|
+
const fieldType = types[field];
|
|
263
110
|
|
|
264
111
|
// Null string?
|
|
265
112
|
if (csv && value === 'null') {
|
|
@@ -268,7 +115,7 @@ export function validateData(data, csv = false) {
|
|
|
268
115
|
// Number field
|
|
269
116
|
} else if (fieldType === 'number') {
|
|
270
117
|
if (csv && typeof value === 'string') {
|
|
271
|
-
const numberValue =
|
|
118
|
+
const numberValue = parseNumber(value);
|
|
272
119
|
if (numberValue === null) {
|
|
273
120
|
throwFieldError(field, fieldType, value);
|
|
274
121
|
}
|
|
@@ -280,12 +127,12 @@ export function validateData(data, csv = false) {
|
|
|
280
127
|
// Datetime field
|
|
281
128
|
} else if (fieldType === 'datetime') {
|
|
282
129
|
if (typeof value === 'string') {
|
|
283
|
-
const datetimeValue =
|
|
130
|
+
const datetimeValue = parseDatetime(value);
|
|
284
131
|
if (datetimeValue === null) {
|
|
285
132
|
throwFieldError(field, fieldType, value);
|
|
286
133
|
}
|
|
287
134
|
row[field] = datetimeValue;
|
|
288
|
-
} else if (value !== null && !(value instanceof
|
|
135
|
+
} else if (value !== null && !(value instanceof Date)) {
|
|
289
136
|
throwFieldError(field, fieldType, value);
|
|
290
137
|
}
|
|
291
138
|
|
|
@@ -302,220 +149,380 @@ export function validateData(data, csv = false) {
|
|
|
302
149
|
}
|
|
303
150
|
|
|
304
151
|
|
|
152
|
+
function parseNumber(text) {
|
|
153
|
+
const value = Number.parseFloat(text);
|
|
154
|
+
if (Number.isNaN(value) || !Number.isFinite(value)) {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
return value;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
function parseDatetime(text) {
|
|
162
|
+
if (rDate.test(text)) {
|
|
163
|
+
const localDate = new Date(text);
|
|
164
|
+
return new Date(localDate.getUTCFullYear(), localDate.getUTCMonth(), localDate.getUTCDate());
|
|
165
|
+
} else if (rDatetime.test(text)) {
|
|
166
|
+
return new Date(text);
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const rDate = /^\d{4}-\d{2}-\d{2}$/;
|
|
172
|
+
const rDatetime = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
173
|
+
|
|
174
|
+
|
|
305
175
|
/**
|
|
306
|
-
*
|
|
176
|
+
* Join two data arrays
|
|
307
177
|
*
|
|
308
|
-
* @param {Object
|
|
309
|
-
* @param {
|
|
310
|
-
* @param {string}
|
|
311
|
-
* @param {
|
|
312
|
-
* @
|
|
178
|
+
* @param {Object} leftData - The left data array
|
|
179
|
+
* @param {Object} rightData - The left data array
|
|
180
|
+
* @param {string} joinExpr - The join [expression]{@link https://craigahobbs.github.io/calc-script/language/#expressions}
|
|
181
|
+
* @param {?string} [rightExpr = null] - The right join [expression]{@link https://craigahobbs.github.io/calc-script/language/#expressions}
|
|
182
|
+
* @param {boolean} [isLeftJoin = false] - If true, perform a left join (always include left row)
|
|
183
|
+
* @param {?Object} [variables = null] - Additional variables for expression evaluation
|
|
184
|
+
* @returns {Object[]} The joined data array
|
|
313
185
|
*/
|
|
314
|
-
export function
|
|
315
|
-
//
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
186
|
+
export function joinData(leftData, rightData, joinExpr, rightExpr = null, isLeftJoin = false, variables = null) {
|
|
187
|
+
// Compute the map of row field name to joined row field name
|
|
188
|
+
const leftNames = {};
|
|
189
|
+
for (const row of leftData) {
|
|
190
|
+
for (const fieldName of Object.keys(row)) {
|
|
191
|
+
if (!(fieldName in leftNames)) {
|
|
192
|
+
leftNames[fieldName] = fieldName;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const rightNames = {};
|
|
197
|
+
for (const row of rightData) {
|
|
198
|
+
for (const fieldName of Object.keys(row)) {
|
|
199
|
+
if (!(fieldName in rightNames)) {
|
|
200
|
+
if (!(fieldName in leftNames)) {
|
|
201
|
+
rightNames[fieldName] = fieldName;
|
|
202
|
+
} else {
|
|
203
|
+
let uniqueName = fieldName;
|
|
204
|
+
let ixUnique = 2;
|
|
205
|
+
do {
|
|
206
|
+
uniqueName = `${fieldName}${ixUnique}`;
|
|
207
|
+
ixUnique += 1;
|
|
208
|
+
} while (uniqueName in leftNames || uniqueName in rightNames);
|
|
209
|
+
rightNames[fieldName] = uniqueName;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
321
214
|
|
|
322
|
-
//
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
215
|
+
// Parse the left and right expressions
|
|
216
|
+
const evalOptions = (variables !== null ? {'globals': variables} : null);
|
|
217
|
+
const leftExpression = parseExpression(joinExpr);
|
|
218
|
+
const rightExpression = (rightExpr !== null ? parseExpression(rightExpr) : leftExpression);
|
|
219
|
+
|
|
220
|
+
// Bucket the right rows by the right expression value
|
|
221
|
+
const rightCategoryRows = {};
|
|
222
|
+
for (const rightRow of rightData) {
|
|
223
|
+
const categoryKey = JSON.stringify(evaluateExpression(rightExpression, evalOptions, rightRow));
|
|
224
|
+
if (!(categoryKey in rightCategoryRows)) {
|
|
225
|
+
rightCategoryRows[categoryKey] = [];
|
|
226
|
+
}
|
|
227
|
+
rightCategoryRows[categoryKey].push(rightRow);
|
|
228
|
+
}
|
|
327
229
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
230
|
+
// Join the left with the right
|
|
231
|
+
const data = [];
|
|
232
|
+
for (const leftRow of leftData) {
|
|
233
|
+
const categoryKey = JSON.stringify(evaluateExpression(leftExpression, evalOptions, leftRow));
|
|
234
|
+
if (categoryKey in rightCategoryRows) {
|
|
235
|
+
for (const rightRow of rightCategoryRows[categoryKey]) {
|
|
236
|
+
const joinRow = {...leftRow};
|
|
237
|
+
for (const [rightName, rightValue] of Object.entries(rightRow)) {
|
|
238
|
+
joinRow[rightNames[rightName]] = rightValue;
|
|
239
|
+
}
|
|
240
|
+
data.push(joinRow);
|
|
241
|
+
}
|
|
242
|
+
} else if (!isLeftJoin) {
|
|
243
|
+
data.push({...leftRow});
|
|
331
244
|
}
|
|
332
245
|
}
|
|
333
246
|
|
|
334
|
-
return
|
|
247
|
+
return data;
|
|
335
248
|
}
|
|
336
249
|
|
|
337
250
|
|
|
338
251
|
/**
|
|
339
|
-
*
|
|
252
|
+
* Add a calculated field to each row of a data array
|
|
340
253
|
*
|
|
341
|
-
* @param {
|
|
342
|
-
* @
|
|
254
|
+
* @param {Object[]} data - The data array. Row objects are updated with the calculated field values.
|
|
255
|
+
* @param {string} fieldName - The calculated field name
|
|
256
|
+
* @param {string} expr - The calculated field expression
|
|
257
|
+
* @param {?Object} [variables = null] - Additional variables for expression evaluation
|
|
258
|
+
* @returns {Object[]} The updated data array
|
|
343
259
|
*/
|
|
344
|
-
export function
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
260
|
+
export function addCalculatedField(data, fieldName, expr, variables = null) {
|
|
261
|
+
// Parse the calculation expression
|
|
262
|
+
const calcExpr = parseExpression(expr);
|
|
263
|
+
|
|
264
|
+
// Compute the calculated field for each row
|
|
265
|
+
const evalOptions = (variables !== null ? {'globals': variables} : null);
|
|
266
|
+
for (const row of data) {
|
|
267
|
+
row[fieldName] = evaluateExpression(calcExpr, evalOptions, row);
|
|
349
268
|
}
|
|
350
|
-
return
|
|
269
|
+
return data;
|
|
351
270
|
}
|
|
352
271
|
|
|
353
272
|
|
|
354
273
|
/**
|
|
355
274
|
* Filter data rows
|
|
356
275
|
*
|
|
357
|
-
* @param {Object[]} data - The data array
|
|
358
|
-
* @param {string} expr - The boolean filter expression
|
|
359
|
-
* @param {Object} [variables = null] -
|
|
276
|
+
* @param {Object[]} data - The data array
|
|
277
|
+
* @param {string} expr - The boolean filter [expression]{@link https://craigahobbs.github.io/calc-script/language/#expressions}
|
|
278
|
+
* @param {?Object} [variables = null] - Additional variables for expression evaluation
|
|
360
279
|
* @returns {Object[]} The filtered data array
|
|
361
280
|
*/
|
|
362
281
|
export function filterData(data, expr, variables = null) {
|
|
282
|
+
const result = [];
|
|
283
|
+
|
|
363
284
|
// Parse the filter expression
|
|
364
285
|
const filterExpr = parseExpression(expr);
|
|
365
286
|
|
|
366
|
-
// Compute the data variable values
|
|
367
|
-
const dataVariables = variables ?? createDataVariables(null);
|
|
368
|
-
const evalOptions = {'globals': dataVariables};
|
|
369
|
-
|
|
370
287
|
// Filter the data
|
|
371
|
-
const
|
|
288
|
+
const evalOptions = (variables !== null ? {'globals': variables} : null);
|
|
372
289
|
for (const row of data) {
|
|
373
290
|
if (evaluateExpression(filterExpr, evalOptions, row)) {
|
|
374
|
-
|
|
291
|
+
result.push(row);
|
|
375
292
|
}
|
|
376
293
|
}
|
|
377
|
-
|
|
294
|
+
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
// The aggregation model
|
|
300
|
+
export const aggregationTypes = parseSchemaMarkdown(`\
|
|
301
|
+
group "Aggregation"
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# A data aggregation specification
|
|
305
|
+
struct Aggregation
|
|
306
|
+
|
|
307
|
+
# The aggregation category fields
|
|
308
|
+
optional string[len > 0] categories
|
|
309
|
+
|
|
310
|
+
# The aggregation measures
|
|
311
|
+
AggregationMeasure[len > 0] measures
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
# An aggregation measure specification
|
|
315
|
+
struct AggregationMeasure
|
|
316
|
+
|
|
317
|
+
# The aggregation measure field
|
|
318
|
+
string field
|
|
319
|
+
|
|
320
|
+
# The aggregation function
|
|
321
|
+
AggregationFunction function
|
|
322
|
+
|
|
323
|
+
# The aggregated-measure field name
|
|
324
|
+
optional string name
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
# An aggregation function
|
|
328
|
+
enum AggregationFunction
|
|
329
|
+
|
|
330
|
+
# The average of the measure's values
|
|
331
|
+
average
|
|
332
|
+
|
|
333
|
+
# The count of the measure's values
|
|
334
|
+
count
|
|
335
|
+
|
|
336
|
+
# The greatest of the measure's values
|
|
337
|
+
max
|
|
338
|
+
|
|
339
|
+
# The least of the measure's values
|
|
340
|
+
min
|
|
341
|
+
|
|
342
|
+
# The sum of the measure's values
|
|
343
|
+
sum
|
|
344
|
+
`);
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Validate an aggregation model
|
|
349
|
+
*
|
|
350
|
+
* @param {Object} aggregation - The
|
|
351
|
+
* [aggregation model]{@link https://craigahobbs.github.io/markdown-up/library/model.html#var.vName='Aggregation'}
|
|
352
|
+
* @returns {Object} The validated
|
|
353
|
+
* [aggregation model]{@link https://craigahobbs.github.io/markdown-up/library/model.html#var.vName='Aggregation'}
|
|
354
|
+
* @throws [ValidationError]{@link https://craigahobbs.github.io/schema-markdown-js/module-lib_schema.ValidationError.html}
|
|
355
|
+
*/
|
|
356
|
+
export function validateAggregation(aggregation) {
|
|
357
|
+
return validateType(aggregationTypes, 'Aggregation', aggregation);
|
|
378
358
|
}
|
|
379
359
|
|
|
380
360
|
|
|
381
361
|
/**
|
|
382
362
|
* Aggregate data rows
|
|
383
363
|
*
|
|
384
|
-
* @param {Object} aggregationModel - The aggregation model
|
|
385
364
|
* @param {Object[]} data - The data array
|
|
386
|
-
* @param {Object}
|
|
387
|
-
*
|
|
365
|
+
* @param {Object} aggregation - The
|
|
366
|
+
* [aggregation model]{@link https://craigahobbs.github.io/markdown-up/library/model.html#var.vName='Aggregation'}
|
|
367
|
+
* @returns {Object[]} The aggregated data array
|
|
388
368
|
*/
|
|
389
|
-
export function aggregateData(
|
|
390
|
-
|
|
391
|
-
const aggregateTypes = {};
|
|
392
|
-
for (const categoryField of aggregationModel.category) {
|
|
393
|
-
if (!(categoryField in types)) {
|
|
394
|
-
throw new Error(`Unknown aggregation category field "${categoryField}"`);
|
|
395
|
-
}
|
|
396
|
-
aggregateTypes[categoryField] = types[categoryField];
|
|
397
|
-
}
|
|
398
|
-
for (const measure of aggregationModel.measure) {
|
|
399
|
-
if (!(measure.field in types)) {
|
|
400
|
-
throw new Error(`Unknown aggregation category field "${measure.field}"`);
|
|
401
|
-
}
|
|
402
|
-
if ((measure.func === 'Average' || measure.func === 'Sum') && types[measure.field] !== 'number') {
|
|
403
|
-
throw new Error(`Invalid aggregation measure function "${measure.func}" ` +
|
|
404
|
-
`for field "${measure.field}" (type "${types[measure.field]}")`);
|
|
405
|
-
}
|
|
406
|
-
const measureName = ('name' in measure ? measure.name : measure.field);
|
|
407
|
-
aggregateTypes[measureName] = types[measure.field];
|
|
408
|
-
}
|
|
369
|
+
export function aggregateData(data, aggregation) {
|
|
370
|
+
const categories = aggregation.categories ?? null;
|
|
409
371
|
|
|
410
372
|
// Create the aggregate rows
|
|
411
|
-
const
|
|
373
|
+
const categoryRows = {};
|
|
412
374
|
for (const row of data) {
|
|
413
375
|
// Compute the category values
|
|
414
|
-
const categoryValues =
|
|
376
|
+
const categoryValues = (categories !== null ? categories.map((categoryField) => row[categoryField]) : null);
|
|
415
377
|
|
|
416
378
|
// Get or create the aggregate row
|
|
417
379
|
let aggregateRow;
|
|
418
|
-
const rowKey = JSON.stringify(categoryValues);
|
|
419
|
-
if (rowKey in
|
|
420
|
-
aggregateRow =
|
|
380
|
+
const rowKey = (categoryValues !== null ? JSON.stringify(categoryValues) : '');
|
|
381
|
+
if (rowKey in categoryRows) {
|
|
382
|
+
aggregateRow = categoryRows[rowKey];
|
|
421
383
|
} else {
|
|
422
384
|
aggregateRow = {};
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
385
|
+
categoryRows[rowKey] = aggregateRow;
|
|
386
|
+
if (categories !== null) {
|
|
387
|
+
for (let ixCategoryField = 0; ixCategoryField < categories.length; ixCategoryField++) {
|
|
388
|
+
aggregateRow[categories[ixCategoryField]] = categoryValues[ixCategoryField];
|
|
389
|
+
}
|
|
426
390
|
}
|
|
427
391
|
}
|
|
428
392
|
|
|
429
393
|
// Add to the aggregate measure values
|
|
430
|
-
for (const measure of
|
|
431
|
-
const
|
|
432
|
-
const value =
|
|
433
|
-
if (
|
|
434
|
-
|
|
435
|
-
aggregateRow[measureName] = [];
|
|
436
|
-
}
|
|
437
|
-
aggregateRow[measureName].push(value);
|
|
394
|
+
for (const measure of aggregation.measures) {
|
|
395
|
+
const field = measure.name ?? measure.field;
|
|
396
|
+
const value = row[measure.field] ?? null;
|
|
397
|
+
if (!(field in aggregateRow)) {
|
|
398
|
+
aggregateRow[field] = [];
|
|
438
399
|
}
|
|
400
|
+
aggregateRow[field].push(value);
|
|
439
401
|
}
|
|
440
402
|
}
|
|
441
403
|
|
|
442
404
|
// Compute the measure values aggregate function value
|
|
443
|
-
const aggregateRows = Object.values(
|
|
405
|
+
const aggregateRows = Object.values(categoryRows);
|
|
444
406
|
for (const aggregateRow of aggregateRows) {
|
|
445
|
-
for (const measure of
|
|
446
|
-
const
|
|
447
|
-
const
|
|
448
|
-
const
|
|
449
|
-
if (
|
|
450
|
-
aggregateRow[
|
|
451
|
-
} else if (
|
|
452
|
-
aggregateRow[
|
|
453
|
-
} else if (
|
|
454
|
-
aggregateRow[
|
|
455
|
-
} else if (
|
|
456
|
-
aggregateRow[
|
|
457
|
-
} else
|
|
458
|
-
aggregateRow[
|
|
459
|
-
} else if (measureFunction === 'Sum') {
|
|
460
|
-
aggregateRow[measureName] = measureValues.reduce((sum, val) => sum + val);
|
|
407
|
+
for (const measure of aggregation.measures) {
|
|
408
|
+
const field = measure.name ?? measure.field;
|
|
409
|
+
const func = measure.function;
|
|
410
|
+
const measureValues = aggregateRow[field];
|
|
411
|
+
if (func === 'count') {
|
|
412
|
+
aggregateRow[field] = measureValues.length;
|
|
413
|
+
} else if (func === 'max') {
|
|
414
|
+
aggregateRow[field] = measureValues.reduce((max, val) => (val > max ? val : max));
|
|
415
|
+
} else if (func === 'min') {
|
|
416
|
+
aggregateRow[field] = measureValues.reduce((min, val) => (val < min ? val : min));
|
|
417
|
+
} else if (func === 'sum') {
|
|
418
|
+
aggregateRow[field] = measureValues.reduce((sum, val) => sum + val, 0);
|
|
419
|
+
} else {
|
|
420
|
+
aggregateRow[field] = measureValues.reduce((sum, val) => sum + val, 0) / measureValues.length;
|
|
461
421
|
}
|
|
462
422
|
}
|
|
463
423
|
}
|
|
464
424
|
|
|
465
|
-
return
|
|
425
|
+
return aggregateRows;
|
|
466
426
|
}
|
|
467
427
|
|
|
468
428
|
|
|
469
429
|
/**
|
|
470
430
|
* Sort data rows
|
|
471
431
|
*
|
|
472
|
-
* @param {Object}
|
|
473
|
-
* @param {Object[]}
|
|
432
|
+
* @param {Object[]} data - The data array
|
|
433
|
+
* @param {Object[]} sorts - The sort field-name/descending-sort tuples
|
|
434
|
+
* @returns {Object[]} The sorted data array
|
|
474
435
|
*/
|
|
475
|
-
export function sortData(
|
|
476
|
-
data.sort((row1, row2) =>
|
|
436
|
+
export function sortData(data, sorts) {
|
|
437
|
+
return data.sort((row1, row2) => sorts.reduce((result, sort) => {
|
|
477
438
|
if (result !== 0) {
|
|
478
439
|
return result;
|
|
479
440
|
}
|
|
480
|
-
const
|
|
481
|
-
const
|
|
441
|
+
const [field, desc = false] = sort;
|
|
442
|
+
const value1 = row1[field] ?? null;
|
|
443
|
+
const value2 = row2[field] ?? null;
|
|
482
444
|
const compare = compareValues(value1, value2);
|
|
483
|
-
return
|
|
445
|
+
return desc ? -compare : compare;
|
|
484
446
|
}, 0));
|
|
485
447
|
}
|
|
486
448
|
|
|
487
449
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
450
|
+
// Helper function to format labels
|
|
451
|
+
export function formatValue(value, precision = null, datetime = null) {
|
|
452
|
+
if (value instanceof Date) {
|
|
453
|
+
if (datetime === 'year') {
|
|
454
|
+
// Round to nearest year
|
|
455
|
+
let valueRounded = value;
|
|
456
|
+
if (value.getUTCMonth() > 5) {
|
|
457
|
+
valueRounded = new Date(value);
|
|
458
|
+
valueRounded.setUTCFullYear(value.getUTCFullYear() + 1);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const isoFormat = valueRounded.toISOString();
|
|
462
|
+
return isoFormat.slice(0, isoFormat.indexOf('T') - 6);
|
|
463
|
+
} else if (datetime === 'month') {
|
|
464
|
+
// Round to the nearest month
|
|
465
|
+
let valueRounded = value;
|
|
466
|
+
if (value.getUTCDate() > 15) {
|
|
467
|
+
valueRounded = new Date(value);
|
|
468
|
+
valueRounded.setMonth(value.getUTCMonth() + 1);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const isoFormat = valueRounded.toISOString();
|
|
472
|
+
return isoFormat.slice(0, isoFormat.indexOf('T') - 3);
|
|
473
|
+
} else if (datetime === 'day') {
|
|
474
|
+
const isoFormat = value.toISOString();
|
|
475
|
+
return isoFormat.slice(0, isoFormat.indexOf('T'));
|
|
505
476
|
}
|
|
506
|
-
|
|
477
|
+
return value.toISOString().replace(rDateCleanup, '');
|
|
478
|
+
} else if (typeof value === 'number') {
|
|
479
|
+
const numberFormat = value.toFixed(precision ?? defaultPrecision);
|
|
480
|
+
return numberFormat.replace(rNumberCleanup, '');
|
|
507
481
|
}
|
|
482
|
+
return `${value}`;
|
|
483
|
+
}
|
|
508
484
|
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
485
|
+
const defaultPrecision = 2;
|
|
486
|
+
const rNumberCleanup = /\.0*$/;
|
|
487
|
+
const rDateCleanup = /(?:(?:(?:-01)?T00:00)?:00)?\.\d\d\dZ$/;
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
// Helper function to compare values
|
|
491
|
+
export function compareValues(value1, value2) {
|
|
492
|
+
if (value1 === null) {
|
|
493
|
+
return value2 === null ? 0 : -1;
|
|
494
|
+
} else if (value2 === null) {
|
|
495
|
+
return 1;
|
|
496
|
+
} else if (value1 instanceof Date) {
|
|
497
|
+
const time1 = value1.getTime();
|
|
498
|
+
const time2 = value2.getTime();
|
|
499
|
+
return time1 < time2 ? -1 : (time1 === time2 ? 0 : 1);
|
|
500
|
+
}
|
|
501
|
+
return value1 < value2 ? -1 : (value1 === value2 ? 0 : 1);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
// Helper function to compute a value's parameter
|
|
506
|
+
export function valueParameter(value, minValue, maxValue) {
|
|
507
|
+
if (minValue === maxValue) {
|
|
508
|
+
return 0;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
if (minValue instanceof Date) {
|
|
512
|
+
const minDateValue = minValue.valueOf();
|
|
513
|
+
return (value.valueOf() - minDateValue) / (maxValue.valueOf() - minDateValue);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
return (value - minValue) / (maxValue - minValue);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
// Helper function to compute a value from a parameter
|
|
521
|
+
export function parameterValue(param, minValue, maxValue) {
|
|
522
|
+
if (minValue instanceof Date) {
|
|
523
|
+
const minDateValue = minValue.valueOf();
|
|
524
|
+
return new Date(minDateValue + param * (maxValue.valueOf() - minDateValue));
|
|
518
525
|
}
|
|
519
526
|
|
|
520
|
-
return
|
|
527
|
+
return minValue + param * (maxValue - minValue);
|
|
521
528
|
}
|