This repository has been archived by the owner on Mar 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
81 lines (60 loc) · 1.72 KB
/
index.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
'use strict'
// ====================================================================
var forEach = require('lodash/forEach')
var moment = require('moment')
// ====================================================================
var EOL = '\n'
function encode (val, attr) {
var type = (attr && attr.type) || 'string'
if (type === 'numeric') {
return +val
}
if (type === 'date') {
val = moment.utc(val).format(attr.format)
}
return JSON.stringify(val)
}
function isDefined (val) {
return val != null
}
// ====================================================================
exports.format = exports.stringify = function format (relation) {
var arff = []
var name = relation.relation
if (isDefined(name)) {
arff.push('@RELATION ', name, EOL, EOL)
}
var attributes = relation.attributes
forEach(attributes, function (attr) {
arff.push('@ATTRIBUTE ', attr.name, ' ')
var type = attr.type
if (type === 'date') {
arff.push('date')
if (attr.format) {
arff.push(' ', encode(attr.format))
}
} else if (type === 'enum') {
arff.push('{')
forEach(attr.values, function (value) {
arff.push(encode(value), ',')
})
// Replace trailing comma with closing bracket.
arff[arff.length - 1] = '}'
} else {
arff.push(type)
}
arff.push(EOL)
})
arff.push(EOL)
arff.push('@DATA', EOL)
forEach(relation.data, function (datum) {
forEach(attributes, function (attr) {
var value = datum[attr.name]
arff.push(isDefined(value) ? encode(value, attr) : '?', ',')
})
// Replace trailing comma with a EOL.
arff[arff.length - 1] = EOL
})
return arff.join('')
}
exports.parse = require('./parser').parse