-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
94 lines (77 loc) · 2.5 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
82
83
84
85
86
87
88
89
90
91
92
93
94
(function(){
var br = "\n"
function extend (o) {
Array.prototype.slice.call(arguments, 1).forEach(function(source){
if (!source) return
for (var keys = Object.keys(source), i = 0; i < keys.length; i++) {
var key = keys[i]
o[key] = source[key]
}
})
return o
}
function unquote (str) {
var match
return (match = str.match(/(['"]?)(.*)\1/)) && match[2] || str
}
function comments (line) {
return !/#@/.test(line[0])
}
function getValues (line, sep) {
return line.split(sep).map(function(value){
var value = unquote(value);
var num = +value;
return (num.toString() === value) ? num : value; // take advantage of NaN !== NaN
})
}
function Parser (sep, options) {
var opt = extend({
header: true
}, options)
this.sep = sep
this.header = opt.header
}
Parser.prototype.stringify = function (data) {
var sep = this.sep
, head = !!this.header
, keys = (typeof data[0] === 'object') && Object.keys(data[0])
, header = keys && keys.join(sep)
, output = head ? (header + br) : ''
if (!data || !keys) return ''
return output + data.map(function(obj){
var item = keys ? {} : []
var values = keys.reduce(function(p, key){
p.push(obj[key])
return p
}, [])
return values.join(sep)
}).join(br)
}
Parser.prototype.parse = function (tsv) {
var sep = this.sep
, lines = tsv.split(/[\n\r]/).filter(comments)
, head = !!this.header
, keys = head ? getValues(lines.shift(), sep) : {}
if (lines.length < 1) return []
return lines.reduce(function(output, line){
var item = head ? {} : []
output.push(getValues(line, sep).reduce(function(item, val, i){
item[keys[i] || i] = val
return item
}, item))
return output
}, [])
}
// Export TSV parser as main, but also expose `.TSV`, `.CSV` and `.Parser`.
var TSV = new Parser("\t")
extend(TSV, {
TSV : TSV
, CSV : new Parser(",")
, Parser : Parser
})
if (typeof module !== 'undefined' && module.exports){
module.exports = TSV
} else {
this.TSV = TSV
}
}).call(this)