blob: e01e77217bb62c872be1b8ccbcca7efe31b59720 [file] [log] [blame]
Matteo Scandoloa5d03d52016-07-21 11:35:46 -07001(function() {
2 'use strict';
3
4 /**
5 * @ngdoc service
6 * @name xos.uiComponents.LabelFormatter
7 * @description This factory define a set of helper function to format label started from an object property
8 **/
9
10 angular
11 .module('xos.uiComponents')
12 .factory('LabelFormatter', labelFormatter);
13
14 function labelFormatter() {
15
16 /**
17 * @ngdoc method
18 * @name xos.uiComponents.LabelFormatter#_formatByUnderscore
19 * @methodOf xos.uiComponents.LabelFormatter
20 * @description
21 * Convert a `snake_case` string to readable string.<br/>
22 * Eg: `this_string` will became `this string`
23 * @param {string} string The string to be converted
24 * @returns {string} The converten string
25 **/
26
27 const _formatByUnderscore = string => string.split('_').join(' ').trim();
28
29 /**
30 * @ngdoc method
31 * @name xos.uiComponents.LabelFormatter#_formatByUppercase
32 * @methodOf xos.uiComponents.LabelFormatter
33 * @description
34 * Convert a `camelCase` string to readable string.<br/>
35 * Eg: `thisString` will became `this string`
36 * @param {string} string The string to be converted
37 * @returns {string} The converten string
38 **/
39
40 const _formatByUppercase = string => string.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join(' ');
41
42 /**
43 * @ngdoc method
44 * @name xos.uiComponents.LabelFormatter#_capitalize
45 * @methodOf xos.uiComponents.LabelFormatter
46 * @description
47 * Capitalize the first letter of a string.<br/>
48 * Eg: `this string` will became `This string`
49 * @param {string} string The string to be converted
50 * @returns {string} The converten string
51 **/
52
53 const _capitalize = string => string.slice(0, 1).toUpperCase() + string.slice(1);
54
55 /**
56 * @ngdoc method
57 * @name xos.uiComponents.LabelFormatter#format
58 * @methodOf xos.uiComponents.LabelFormatter
59 * @description
60 * Apply in order:
61 * - _formatByUnderscore
62 * - _formatByUppercase
63 * - _capitalize
64 * - replace multiple space with a single one
Matteo Scandolo1d689852016-09-29 09:42:12 -070065 * - append `:` at the end
Matteo Scandoloa5d03d52016-07-21 11:35:46 -070066 * <br/>
67 * Eg: `this_string` will became `This string:`<br/>
68 * Eg: `thisString` will became `This string:`
69 * @param {string} string The string to be converted
70 * @returns {string} The converten string
71 **/
72
73 const format = (string) => {
74 string = _formatByUnderscore(string);
75 string = _formatByUppercase(string);
76
77 string = _capitalize(string).replace(/\s\s+/g, ' ') + ':';
78 return string.replace('::', ':');
79 };
80
81 return {
82 // test export
83 _formatByUnderscore: _formatByUnderscore,
84 _formatByUppercase: _formatByUppercase,
85 _capitalize: _capitalize,
86 // export to use
87 format: format
88 };
89 }
90})();