UNPKG

1.23 kBJavaScriptView Raw
1'use strict'
2
3var matchingBuckets = require('./matchingBuckets')
4var deepMatch = require('./deepMatch')
5var onlyRegex = require('./onlyRegex')
6
7function Iterator (parent, obj, opts) {
8 if (!(this instanceof Iterator)) {
9 return new Iterator(this, parent, obj)
10 }
11
12 this.parent = parent
13 this.pattern = obj
14 this.onlyPatterns = opts && opts.patterns
15
16 if (obj) {
17 if (onlyRegex(obj)) {
18 this.buckets = parent._buckets
19 } else {
20 this.buckets = matchingBuckets(parent._buckets, obj)
21 }
22 } else {
23 this.buckets = parent._buckets
24 }
25
26 if (this.parent._regexBucket.data.length > 0) {
27 this.buckets.push(this.parent._regexBucket)
28 }
29
30 this.i = 0
31 this.k = 0
32}
33
34Iterator.prototype.next = function () {
35 var match = null
36
37 if (this.i === this.buckets.length) {
38 return null
39 }
40
41 var current = this.buckets[this.i].data[this.k]
42
43 if (!this.pattern || deepMatch(current.pattern, this.pattern)) {
44 if (this.onlyPatterns) {
45 match = current.pattern
46 } else {
47 match = current.payload
48 }
49 }
50
51 if (++this.k === this.buckets[this.i].data.length) {
52 ++this.i
53 this.k = 0
54 }
55
56 if (match) {
57 return match
58 } else {
59 return this.next()
60 }
61}
62
63module.exports = Iterator