Code coverage report for app/utils/string_utils.js

Statements: 91.67% (99 / 108)      Branches: 93.06% (67 / 72)      Functions: 88% (22 / 25)      Lines: 91.59% (98 / 107)      Ignored: none     

All files » app/utils/ » string_utils.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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289    1                                     1       10 10 10   10 1   10 1   10 1     10   9     3 3     2 2 2 2 2     4 4       10     1 6352   6355               15 13 22     2                         100 8   92     92 92 92 92 92 92 87 5 1   4     92 225 225 225 37 37 188 163 25 25 25   163   92       21               3 3 9 9 531 27     9   3                 9 5   4       11 7   4 4                         54 54 54 101 23   78   47 47 16     31       54                       1 7     1       1   7 7                 6 3                                                                         6 1   5 6                   14   14 4        
"use strict";
 
;require.register("utils/string_utils", function (exports, require, module) {
  /**
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
 
  module.exports = {
 
    pad: function pad(str, len, _pad, dir) {
 
      var STR_PAD_LEFT = 1;
      var STR_PAD_RIGHT = 2;
      var STR_PAD_BOTH = 3;
 
      if (typeof len == "undefined") {
        len = 0;
      }
      if (typeof _pad == "undefined") {
        _pad = ' ';
      }
      if (typeof dir == "undefined") {
        dir = STR_PAD_RIGHT;
      }
 
      if (len + 1 >= str.length) {
 
        switch (dir) {
 
          case STR_PAD_LEFT:
            str = Array(len + 1 - str.length).join(_pad) + str;
            break;
 
          case STR_PAD_BOTH:
            var padlen = len - str.length;
            var right = Math.ceil(padlen / 2);
            var left = padlen - right;
            str = Array(left + 1).join(_pad) + str + Array(right + 1).join(_pad);
            break;
 
          default:
            str = str + Array(len + 1 - str.length).join(_pad);
            break;
 
        } // switch
      }
      return str;
    },
    underScoreToCamelCase: function underScoreToCamelCase(name) {
      function replacer(str, p1, p2, offset, s) {
        return str[1].toUpperCase();
      }
      return name.replace(/_\w/g, replacer);
    },
 
    /**
     * Forces given string into upper camel-case representation. The first
     * character of each word will be capitalized with the rest in lower case.
     */
    getCamelCase: function getCamelCase(name) {
      if (name != null) {
        return name.toLowerCase().replace(/(\b\w)/g, function (f) {
          return f.toUpperCase();
        });
      }
      return name;
    },
 
    /**
     * Compare two versions by following rules:
     * first higher than second then return 1
     * first lower than second then return -1
     * first equal to second then return 0
     * @param first {string}
     * @param second {string}
     * @return {number}
     */
    compareVersions: function compareVersions(first, second) {
      if (!(typeof first === 'string' && typeof second === 'string')) {
        return -1;
      }
      Iif (first === '' || second === '') {
        return -1;
      }
      var firstNumbers = first.split(/[\.-]/);
      var secondNumbers = second.split(/[\.-]/);
      var length = 0;
      var i = 0;
      var result = false;
      if (firstNumbers.length === secondNumbers.length) {
        length = firstNumbers.length;
      } else if (firstNumbers.length < secondNumbers.length) {
        length = secondNumbers.length;
      } else {
        length = firstNumbers.length;
      }
 
      while (i < length && !result) {
        firstNumbers[i] = firstNumbers[i] === undefined ? 0 : window.parseInt(firstNumbers[i]);
        secondNumbers[i] = secondNumbers[i] === undefined ? 0 : window.parseInt(secondNumbers[i]);
        if (firstNumbers[i] > secondNumbers[i]) {
          result = 1;
          break;
        } else if (firstNumbers[i] === secondNumbers[i]) {
          result = 0;
        } else Eif (firstNumbers[i] < secondNumbers[i]) {
          result = -1;
          break;
        }
        i++;
      }
      return result;
    },
 
    isSingleLine: function isSingleLine(string) {
      return String(string).trim().indexOf("\n") == -1;
    },
    /**
     * transform array of objects into CSV format content
     * @param array
     * @return {Array}
     */
    arrayToCSV: function arrayToCSV(array) {
      var content = "";
      array.forEach(function (item) {
        var row = [];
        for (var i in item) {
          if (item.hasOwnProperty(i)) {
            row.push(item[i]);
          }
        }
        content += row.join(',') + '\n';
      });
      return content;
    },
 
    /**
     * Extracts filename from linux/unix path
     * @param path
     * @return {string}: filename
     */
    getFileFromPath: function getFileFromPath(path) {
      if (!path || typeof path !== 'string') {
        return '';
      }
      return path.replace(/^.*[\/]/, '');
    },
 
    getPath: function getPath(path) {
      if (!path || typeof path !== 'string' || path[0] != '/') {
        return '';
      }
      var last_slash = path.lastIndexOf('/');
      return last_slash != 0 ? path.substr(0, last_slash) : '/';
    },
 
    /**
     * @method getFormattedStringFromArray Get formatted string of elements to display on the UI
     * Example:
     * var arr = [ambari, bigdata, hadoop]
     * getFormattedStringFromArray(arr);  // ambari, bigdata and hadoop
     * @param array {Array}  Array of elements
     * @param [endSeparator=Em.I18n.t('and')] {String}
     * @returns {String}
     */
    getFormattedStringFromArray: function getFormattedStringFromArray(array, endSeparator) {
      var label = '';
      endSeparator = endSeparator || Em.I18n.t('and');
      array.forEach(function (_arrElement) {
        if (array.length === 1) {
          label = _arrElement;
        } else {
          if (_arrElement !== array[array.length - 1]) {
            // [clients.length - 1]
            label = label + ' ' + _arrElement;
            if (_arrElement !== array[array.length - 2]) {
              label = label + ',';
            }
          } else {
            label = label + ' ' + endSeparator + ' ' + _arrElement;
          }
        }
      }, this);
      return label.trim();
    },
    /**
     * Get plural|singular value of string by related count.
     *
     * @param {Number} count
     * @param {String} singular
     * @param {String} [plural]
     * @return {String}
     * @method pluralize
     */
    pluralize: function (_pluralize) {
      function pluralize(_x, _x2, _x3) {
        return _pluralize.apply(this, arguments);
      }
 
      pluralize.toString = function () {
        return _pluralize.toString();
      };
 
      return pluralize;
    }(function (count, singular, plural) {
      var _plural = plural || pluralize(singular);
      return count > 1 ? _plural : singular;
    }),
 
    /**
     * decode html entities
     * @param {string} string
     * @returns {string}
     */
    htmlEntities: function htmlEntities(string) {
      if (typeof string !== 'string') return "";
      return $("<div/>").text(string).html();
    },
 
    /**
     * Escaping user input to be treated as a literal string within a regular expression
     * get from https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
     * @param {string} str
     * @returns {*}
     */
    escapeRegExp: function escapeRegExp(str) {
      return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    },
 
    /**
     * Generates random string using upper and lower letters and digits
     *
     * @param {number} len
     * @param {String} [allowed]
     * @returns {String}
     * @method getRandomString
     */
    getRandomString: function getRandomString(len, allowed) {
      Em.assert('len should be defined and more than 0', len > 0);
      var text = '';
      allowed = typeof allowed === 'string' ? allowed : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      for (var i = 0; i < len; i++) {
        text += allowed.charAt(Math.floor(Math.random() * allowed.length));
      }
      return text;
    },
 
    /**
     * @param {string} string
     * @returns {string}
     * @method upperUnderscoreToText
     */
    upperUnderscoreToText: function upperUnderscoreToText(string) {
      if (typeof string !== 'string') {
        return '';
      }
      return string.split('_').map(function (word) {
        return word.toLowerCase().capitalize();
      }).join(' ');
    },
 
    /**
     *
     * @param {string} string
     * @param {RegExp} regexp
     */
    unicodeEscape: function unicodeEscape(string) {
      var regexp = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /[\s\S]/g;
 
      return string.replace(regexp, function (escape) {
        return "\\u" + ('0000' + escape.charCodeAt().toString(16)).slice(-4);
      });
    }
  };
});