all files / app/components/shortenName/ shortenName.service.js

100% Statements 25/25
100% Branches 15/15
100% Functions 8/8
100% Lines 25/25
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                          228×                     428×   428×   250× 250× 250× 26× 26× 26×   22×       428×     24×     51×     23×       23×     23×          
/**
 * @ngdoc service
 * @name app.components.shortenName
 * @description
 * Shortens a full first name and full last name to full first name and last name initial
 */
(function () {
  'use strict';
 
  angular
    .module('app.components')
    .factory('shortenName', factory);
 
  /** @ngInject */
  function factory() {
 
    return shortenName;
 
    /**
     * @ngdoc function
     * @name shortenName
     * @methodOf app.components.shortenName
     *
     * @param {String} name
     * first name and last name
     * @returns {String} name
     */
    function shortenName(name) {
      var result = name;
 
      if (result) {
        // Remove extraneous white space
        result = result.trim().replace(/ +/g, " ");
        var names = result.split(" ");
        if (names.length == 2) {
          var firstName = names[0];
          var lastName = names[1];
          if (!isInitialed(firstName) && !isInitialed(lastName) && !isShortName(lastName) &&
            isProperNoun(lastName)) {
            result = firstName + ' ' + lastName.substr(0, 1) + '.';
          }
        }
      }
      return result;
    }
 
    function isShortName(name) {
      return name.length <= 2;
    }
 
    function isInitialed(name) {
      return name && name.charAt(name.length-1) == '.';
    }
 
    function isProperNoun(name) {
      return name.length >= 2 &&
        isUpper(name.charAt(0)) &&
          isLower(name.charAt(1));
 
      function isUpper(c) {
        return c.toUpperCase() == c;
      }
 
      function isLower(c) {
        return c.toLowerCase() == c;
      }
    }
  }
})();