This repository has been archived by the owner on May 20, 2020. It is now read-only.
forked from watson/cheerio-advanced-selectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (71 loc) · 2.04 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
'use strict'
var util = require('util')
var splitter = /^(.*?)(?:\:(eq|first|last)(?:\((\d+)\))?)(.*)/
exports.wrap = function (Cheerio) {
var CheerioAdv = function (selector, context, root, opts) {
if (!(this instanceof CheerioAdv)) return new CheerioAdv(selector, context, root, opts)
if (typeof selector === 'string' && splitter.test(selector)) {
var steps = split(selector)
var cursor = Cheerio(steps.shift(), context, root, opts)
return execSteps(cursor, steps)
}
return Cheerio.apply(Cheerio, arguments)
}
util.inherits(CheerioAdv, Cheerio)
CheerioAdv.load = function () {
var $ = Cheerio.load.apply(Cheerio, arguments)
return function (selector, context, root) {
if (typeof selector === 'string') return exports.find($, selector, context, root)
return $.apply(Cheerio, arguments)
}
}
return CheerioAdv
}
exports.find = function ($, selector, context, root) {
return exports.compile(selector)($, context, root)
}
exports.compile = function (selector) {
var steps = split(selector)
selector = steps.shift()
return function ($, context, root) {
var cursor = $(selector, context, root)
return execSteps(cursor, steps)
}
}
var split = function (selector) {
var steps = []
var match = selector.match(splitter)
while (match) {
steps.push(match[1])
steps.push(selectors[match[2]](match[3]))
selector = match[4].trim()
match = selector.match(splitter)
}
steps.push(selector)
return steps.filter(function (step) {
return step !== ''
})
}
var execSteps = function (cursor, steps) {
return steps.reduce(function (cursor, step) {
return typeof step === 'function' ? step(cursor) : cursor.find(step)
}, cursor)
}
var selectors = {
eq: function (index) {
index = parseInt(index, 10)
return function (cursor) {
return cursor.eq(index)
}
},
first: function () {
return function (cursor) {
return cursor.first()
}
},
last: function () {
return function (cursor) {
return cursor.last()
}
}
}