1 |
|
2 |
|
3 | /**
|
4 | * Validate a topic to see if it's valid or not.
|
5 | * A topic is valid if it follow below rules:
|
6 | * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
|
7 | * - Rule #2: Part `#` must be located at the end of the mailbox
|
8 | *
|
9 | * @param {String} topic - A topic
|
10 | * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
|
11 | */
|
12 | function validateTopic (topic) {
|
13 | var parts = topic.split('/')
|
14 |
|
15 | for (var i = 0; i < parts.length; i++) {
|
16 | if (parts[i] === '+') {
|
17 | continue
|
18 | }
|
19 |
|
20 | if (parts[i] === '#') {
|
21 | // for Rule #2
|
22 | return i === parts.length - 1
|
23 | }
|
24 |
|
25 | if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
|
26 | return false
|
27 | }
|
28 | }
|
29 |
|
30 | return true
|
31 | }
|
32 |
|
33 | /**
|
34 | * Validate an array of topics to see if any of them is valid or not
|
35 | * @param {Array} topics - Array of topics
|
36 | * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
|
37 | */
|
38 | function validateTopics (topics) {
|
39 | if (topics.length === 0) {
|
40 | return 'empty_topic_list'
|
41 | }
|
42 | for (var i = 0; i < topics.length; i++) {
|
43 | if (!validateTopic(topics[i])) {
|
44 | return topics[i]
|
45 | }
|
46 | }
|
47 | return null
|
48 | }
|
49 |
|
50 | module.exports = {
|
51 | validateTopics: validateTopics
|
52 | }
|