summaryrefslogtreecommitdiff
path: root/bin/wiki/ImportarDesdeURL/node_modules/cheerio-advanced-selectors/index.js
blob: f3dba395acf5c5aab279f3747998d2e15e368419 (plain)
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
95
96
97
'use strict'

var util = require('util')

var splitter = /^(.*?)(?::(eq|(?:(?:first|last)(?!-child)))(?:\((\d+)\))?)(.*)/

exports.wrap = function (Cheerio) {
  function CheerioAdv (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)

    function AdvInitialize (selector, context, root) {
      if (typeof selector === 'string') return exports.find($, selector, context, root)
      return $.apply(Cheerio, arguments)
    }

    Object.keys($).forEach(function (key) {
      AdvInitialize[key] = $[key]
    })

    return AdvInitialize
  }

  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()
    }
  }
}