forked from misterparser/cheerio-tableparser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
64 lines (58 loc) · 1.85 KB
/
index.js
File metadata and controls
64 lines (58 loc) · 1.85 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
/*!
* cheerio-tableparser
* https://github.com/misterparser/cheerio-tableparser
* https://www.npmjs.com/package/cheerio-tableparser
*
* Copyright (c) 2011 Francis Chong
* Copyright (c) 2016 Mister Parser
* Licensed under the MIT licenses.
*
*/
module.exports = function ($) {
$.prototype.parsetable = function (options, cellIterator) {
if (options === undefined) options = {}
if (options.dupCols === undefined) options.dupCols = false
if (options.dupRows === undefined) options.dupRows = false
if (options.textMode === undefined) options.textMode = false
var columns = []
var currX = 0
var currY = 0
$('tr', this).each(function (rowIdx, row) {
currY = 0
$('td, th', row).each(function (colIdx, col) {
var cell = $(col)
var rowspan = parseInt(cell.attr('rowspan') || '1')
var colspan = parseInt(cell.attr('colspan') || '1')
var content = options.textMode === true
? cell.text().trim() || ''
: cell.html() || ''
var x = 0
var y = 0
for (x = 0; x < rowspan; x++) {
for (y = 0; y < colspan; y++) {
if (columns[currY + y] === undefined) {
columns[currY + y] = []
}
while (columns[currY + y][currX + x] !== undefined) {
currY += 1
if (columns[currY + y] === undefined) {
columns[currY + y] = []
}
}
if ((x === 0 || options.dupRows) && (y === 0 || options.dupCols)) {
columns[currY + y][currX + x] = content
if (cellIterator) {
cellIterator({ row: currX + x, col: currY + y }, cell)
}
} else {
columns[currY + y][currX + x] = ''
}
}
}
currY += 1
})
currX += 1
})
return columns
}
}