All files / rxmq.js/src/utils compareTopics.js

100% Statements 19/19
92.86% Branches 13/14
100% Functions 4/4
100% Lines 17/17
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            23x   30x 48x 25x   48x 11x 37x 12x   25x   48x                       2x   25x 2x     23x 23x 23x 23x        
/**
 * Converts topic to search regex
 * @param  {String} topic   Topic name
 * @return {Regex}          Search regex
 * @private
 */
const topicToRegex = topic =>
  `^${topic.split('.').reduce((result, segment, index, arr) => {
    let res = '';
    if (arr[index - 1]) {
      res = arr[index - 1] !== '#' ? '\\.\\b' : '\\b';
    }
    if (segment === '#') {
      res += '[\\s\\S]*';
    } else if (segment === '*') {
      res += '[^.]+';
    } else {
      res += segment;
    }
    return result + res;
  }, '')}$`;
 
/**
 * Compares given topic with existing topic
 * @param  {String}  topic         Topic name
 * @param  {String}  existingTopic Topic name to compare to
 * @return {Boolean}               Whether topic is included in existingTopic
 * @example
 * should(compareTopics('test.one.two', 'test.#')).equal(true);
 * @private
 */
const compareTopics = (topic, existingTopic) => {
  // if no # or * found, do plain string matching
  if (existingTopic.indexOf('#') === -1 && existingTopic.indexOf('*') === -1) {
    return topic === existingTopic;
  }
  // otherwise do regex matching
  const pattern = topicToRegex(existingTopic);
  const rgx = new RegExp(pattern);
  const result = rgx.test(topic);
  return result;
};
 
export { compareTopics };