UNPKG

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