@@ -4,36 +4,46 @@ const { dot } = require('../../../../../api/utils/common');
44 * Personalize function. A factory to create a function which would apply personalization to a given string.
55 *
66 * @param {String } string string to personalize
7- * @param {Object } personaliztion object of {5: {f: 'fallback', c: false, k: 'key'}, 10: {...}} kind
7+ * @param {Object } personalizations object of {5: {f: 'fallback', c: false, k: 'key'}, 10: {...}} kind
88 *
99 * @returns {function } function with single obejct parameter which returns final string for a given data
1010 */
11- module . exports = function personalize ( string , personaliztion ) {
12- let parts = [ ] ,
13- indicies = personaliztion ? Object . keys ( personaliztion ) . map ( n => parseInt ( n , 10 ) ) : [ ] ,
14- i = 0 ,
15- def ;
11+ module . exports = function personalize ( string , personalizations ) {
12+ let parts = [ ] ;
13+ let def ;
14+ let i = 0 ;
15+ let indexes = Object . keys ( personalizations || { } ) . map ( n => parseInt ( n , 10 ) ) ;
1616
17- indicies . forEach ( idx => {
17+ indexes . forEach ( idx => {
1818 if ( i < idx ) {
19- parts . push ( string . substr ( i , idx ) ) ;
19+ const subStringLength = idx - i ;
20+ // push all the string that appears before the personalization index
21+ parts . push ( string . substr ( i , subStringLength ) ) ;
2022 }
23+
24+ // push the personalization function
2125 parts . push ( function ( data ) {
22- let pers = personaliztion [ idx ] ;
23- data = dot ( data , pers . k ) ;
24- if ( pers . c && data ) {
26+ let personalization = personalizations [ idx ] ;
27+
28+ data = dot ( data , personalization . k ) ;
29+
30+ if ( personalization . c && data ) {
2531 if ( typeof data !== 'string' ) {
2632 data = data + '' ;
2733 }
34+
2835 return data . substr ( 0 , 1 ) . toUpperCase ( ) + data . substr ( 1 ) ;
2936 }
30- return data === null || data === undefined ? pers . f : ( data + '' ) ;
37+
38+ // if data does not exist return fallback value
39+ return data === null || data === undefined ? personalization . f : ( data + '' ) ;
3140 } ) ;
32- i = idx + 1 ;
41+
42+ i = idx ;
3343 } ) ;
3444
3545 if ( i < string . length ) {
36- parts . push ( string . substr ( i , string . length ) ) ;
46+ parts . push ( string . substr ( i ) ) ;
3747 }
3848
3949 /**
@@ -48,11 +58,12 @@ module.exports = function personalize(string, personaliztion) {
4858 return parts . map ( p => typeof p === 'string' ? p : p ( data ) ) . join ( '' ) ;
4959 }
5060 }
61+
5162 return def ;
5263 } ;
5364
5465 // a message with all slots filled with default values
5566 def = compile ( { ___dummy : true } ) ;
5667
5768 return compile ;
58- } ;
69+ } ;
0 commit comments