forked from RangerMauve/mqtt-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (50 loc) · 1.47 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
"use strict";
var SEPARATOR = "/";
var SINGLE = "+";
var ALL = "#";
module.exports = {
matches: matches,
extract: extract,
exec: exec,
};
function exec(pattern, topic) {
return matches(pattern, topic) ? extract(pattern, topic) : null;
}
function matches(pattern, topic) {
var patternSegments = pattern.split(SEPARATOR);
var topicSegments = topic.split(SEPARATOR);
var patternLength = patternSegments.length;
var topicLength = topicSegments.length;
var lastIndex = patternLength - 1;
for(var i = 0; i < patternLength; i++){
var currentPattern = patternSegments[i];
var patternChar = currentPattern[0];
var currentTopic = topicSegments[i];
if(!currentTopic && currentPattern !== ALL) return false;
// Only allow # at end
if(patternChar === ALL)
return i === lastIndex;
if(patternChar !== SINGLE && currentPattern !== currentTopic)
return false;
}
return patternLength === topicLength;
}
function extract(pattern, topic) {
var params = {};
var patternSegments = pattern.split(SEPARATOR);
var topicSegments = topic.split(SEPARATOR);
var patternLength = patternSegments.length;
for(var i = 0; i < patternLength; i++){
var currentPattern = patternSegments[i];
var patternChar = currentPattern[0];
if(currentPattern.length === 1)
continue;
if(patternChar === ALL){
params[currentPattern.slice(1)] = topicSegments.slice(i);
break;
} else if(patternChar === SINGLE){
params[currentPattern.slice(1)] = topicSegments[i];
}
}
return params;
}