-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlame-csv.js
More file actions
74 lines (58 loc) · 1.63 KB
/
lame-csv.js
File metadata and controls
74 lines (58 loc) · 1.63 KB
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
var _ = require('../lib/underscore');
function lameCSV(str) {
var rows = str.split('\n');
return _.reduce(rows, function(table, row) {
var cols = row.split(',');
table.push(_.map(cols, function(c) {
return c.trim();
}));
return table;
}, []);
}
var frameworks = 'framework, language, age\n ' +
'rails, ruby, 10\n' +
'node.js, javascript, 5\n' +
'phoenix, elixir, 1';
var table = lameCSV(frameworks);
console.log(table);
//=> [ [ 'framework', 'language', 'age' ],
//=> [ 'rails', 'ruby', '10' ],
//=> [ 'node.js', 'javascript', '5' ],
//=> [ 'phoenix', 'elixir', '1' ] ]
var sorted = _.rest(table).sort();
console.log(sorted);
//=> [ [ 'node.js', 'javascript', '5' ],
//=> [ 'phoenix', 'elixir', '1' ],
//=> [ 'rails', 'ruby', '10' ] ]
function selectFrameworks(table) {
return _.rest(_.map(table, _.first));
}
var frameworkNames = selectFrameworks(table);
console.log(frameworkNames);
//=> [ 'rails', 'node.js', 'phoenix' ]
// more verbose version
function selectFrameworks(table) {
var firstCol = _.map(table, function(row) {
return _.first(row);
});
return _.rest(firstCol);
}
var frameworkNames = selectFrameworks(table);
console.log(frameworkNames);
//=> [ 'rails', 'node.js', 'phoenix' ]
function nth(a, index) {
// lazy version
return a[index];
}
function second(a) {
return nth(a, 1);
}
function selectColumn(table, colNum) {
colNum--; // expects 1-based index
return _.map(table, function(row) {
return nth(row, colNum);
});
}
var col1 = selectColumn(table, 1);
console.log(col1);
//=> [ 'framework', 'rails', 'node.js', 'phoenix' ]