@zohodesk/utils 1.0.0-temp-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +42 -0
  2. package/es/ErrorBoundary.js +29 -0
  3. package/es/StringUtils.js +290 -0
  4. package/es/abbreviateNumber.js +44 -0
  5. package/es/accessKeyCodes.js +18 -0
  6. package/es/applyOpenToCustomize.js +29 -0
  7. package/es/combineCustomStyle.js +39 -0
  8. package/es/compileClassNames.js +29 -0
  9. package/es/constantProps/constant.js +2 -0
  10. package/es/constantProps/index.js +1 -0
  11. package/es/constantProps/uiProps.js +50 -0
  12. package/es/contextFactory.js +15 -0
  13. package/es/createTemplateLiteral.js +77 -0
  14. package/es/crud/ArrayManager.js +63 -0
  15. package/es/crud/ObjectManager.js +54 -0
  16. package/es/crud/arrayCRUD.js +76 -0
  17. package/es/crud/objectCRUD.js +49 -0
  18. package/es/dataTypes.js +25 -0
  19. package/es/debounce.js +12 -0
  20. package/es/deepEqual.js +26 -0
  21. package/es/disCustomStyleProps.js +45 -0
  22. package/es/getCompliedClassName.js +12 -0
  23. package/es/getCompliedCustomId.js +16 -0
  24. package/es/getCurrentTime.js +10 -0
  25. package/es/getCustomBoundingClientRect.js +11 -0
  26. package/es/index.js +11 -0
  27. package/es/isTouchDevice.js +9 -0
  28. package/es/jsonToQueryString.js +6 -0
  29. package/es/loadResource.js +56 -0
  30. package/es/mergeStyle.js +53 -0
  31. package/es/objectUtils.js +4 -0
  32. package/es/omit.js +11 -0
  33. package/es/props/automationProps.js +7 -0
  34. package/es/props/customReducerPropTypes.js +5 -0
  35. package/es/props/customStyleProps.js +9 -0
  36. package/es/props/generalAriaProps.js +6 -0
  37. package/es/props/tagAttributeProps.js +35 -0
  38. package/es/props/tagGeneralAttributeProps.js +35 -0
  39. package/es/props/uiProps.js +95 -0
  40. package/es/reducerHandler.js +18 -0
  41. package/es/renderNode.js +28 -0
  42. package/es/replaceAtFirst.js +3 -0
  43. package/es/replaceAtLast.js +3 -0
  44. package/es/uniqueNumber.js +14 -0
  45. package/package.json +35 -0
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # DOT - Util Collections
2
+
3
+ In this package, We provide lots of util fuctions for web devlopment
4
+
5
+ # 1.3.16
6
+
7
+ - `getCurrentTime`, `objectCRUD`, `arrayCRUD`, `deepEqual`, `ArrayManager`, `ObjectManager` util added.
8
+
9
+ # 1.3.15
10
+
11
+ - **renderNodeUtils**
12
+ - `renderNode` function added to render content that can be either a function or a React element.
13
+ - `isRenderable` function added to check if the content is renderable (either a function or a valid React element).
14
+
15
+ # 1.3.14
16
+
17
+ - **StringUtils**
18
+ - String Utils Methods added
19
+
20
+ # 1.3.13
21
+
22
+ - `mergeStyle` issue fix
23
+
24
+ # 1.3.12
25
+
26
+ - `mergeStyle` functionality updated. Composed classes will also update if it is inside that file.
27
+ ```js
28
+ // Before
29
+ const style = mergeStyle(
30
+ { a: '1', b: '1 2' },
31
+ { a: 'a' }
32
+ );
33
+ // style = { a: '1 a', b: '1 2' }
34
+
35
+ // After
36
+ const style = mergeStyle(
37
+ { a: '1', b: '1 2' },
38
+ { a: 'a' }
39
+ );
40
+ // style = { a: '1 a', b: '1 a 2' }
41
+ ```
42
+ - `compileClassNames` code optimized. Will not support other than object as argument.
@@ -0,0 +1,29 @@
1
+ import React from 'react';
2
+ export default class ErrorBoundary extends React.Component {
3
+ constructor(props) {
4
+ super(props);
5
+ this.state = {
6
+ hasError: false
7
+ };
8
+ }
9
+
10
+ static getDerivedStateFromError(error) {
11
+ return {
12
+ hasError: true,
13
+ error
14
+ };
15
+ }
16
+
17
+ componentDidCatch(error, errorInfo) {
18
+ console.log(error, errorInfo);
19
+ }
20
+
21
+ render() {
22
+ if (this.state.hasError) {
23
+ return this.props.renderFallback(this.state.error);
24
+ }
25
+
26
+ return this.props.children;
27
+ }
28
+
29
+ }
@@ -0,0 +1,290 @@
1
+ /**
2
+ * check given string is empty.
3
+ * @param {string} string - The string to be check.
4
+ */
5
+ export function isEmpty(string) {
6
+ if (!string) {
7
+ return true;
8
+ }
9
+
10
+ return string.length === 0;
11
+ }
12
+ /**
13
+ * check given string is not empty.
14
+ * @param {string} string - Th e string to be check.
15
+ */
16
+
17
+ export function isNotEmpty(string) {
18
+ return !isEmpty(string);
19
+ }
20
+ /**
21
+ * check given string is blank.
22
+ * @param {string} string - The string to be check.
23
+ */
24
+
25
+ export function isBlank(string) {
26
+ if (!string) {
27
+ return true;
28
+ }
29
+
30
+ return !new RegExp('\\S', 'g').test(string);
31
+ }
32
+ /**
33
+ * check given string is not blank.
34
+ * @param {string} string - The string to be check.
35
+ */
36
+
37
+ export function isNotBlank(string) {
38
+ return !isBlank(string);
39
+ }
40
+ /**
41
+ * find index of given char in the string.
42
+ * @param {string} string - The string to be modify.
43
+ */
44
+
45
+ export function indexOf(string, chars, pos) {
46
+ if (string == null || typeof string === undefined) {
47
+ return -1;
48
+ }
49
+
50
+ if (pos) {
51
+ return str.indexOf(chars, typeof pos === undefined ? 0 : pos);
52
+ } else {
53
+ return str.indexOf(chars);
54
+ }
55
+ }
56
+ /**
57
+ * Capitalize the first letter of a string.
58
+ *
59
+ * @param {string} string - The input string to modify.
60
+ * @returns {string} The input string with the first letter capitalized.
61
+ */
62
+
63
+ export function capitalizeFirstLetter(string) {
64
+ return !isStringEmpty(string) ? string.charAt(0).toUpperCase() + string.slice(1) : string;
65
+ }
66
+ /**
67
+ * Encode a string for HTML to prevent cross-site scripting (XSS) attacks.
68
+ *
69
+ * @param {string} str - The input string to encode for HTML.
70
+ * @returns {string} The encoded string safe for inclusion in HTML content.
71
+ */
72
+
73
+ export function encodeForHtml(str) {
74
+ if (/<|>|&|"|'|\\/g.test(str) === true) {
75
+ str = str.replace(/&/g, '&amp;');
76
+ str = str.replace(/</g, '&lt;');
77
+ str = str.replace(/>/g, '&gt;');
78
+ str = str.replace(/"/g, '&quot;');
79
+ str = str.replace(/\\/g, '&#x5c;');
80
+ str = str.replace(/'/g, '&#39;');
81
+ }
82
+
83
+ return str;
84
+ }
85
+ /**
86
+ * Decode HTML entities in a string.
87
+ *
88
+ * @param {string} str - The input string containing HTML-encoded content.
89
+ * @returns {string} The decoded string.
90
+ */
91
+
92
+ export function decodeContent(str) {
93
+ if (/&amp;|&lt;|&gt;|&quot;|&#x5c;|&#39;|&amp;lt;|&amp;gt;/g.test(str) == true) {
94
+ str = str.replace(/&amp;/g, '&');
95
+ str = str.replace(/&lt;|&amp;lt;/g, '<');
96
+ str = str.replace(/&gt;|&amp;gt;/g, '>');
97
+ str = str.replace(/&quot;/g, '"');
98
+ str = str.replace(/&#x5c;/g, '\\');
99
+ str = str.replace(/&#39;/g, "'");
100
+ }
101
+
102
+ return str;
103
+ }
104
+ /**
105
+ * Validatate email.
106
+ *
107
+ * @param {string} email - The input string to validate.
108
+ */
109
+
110
+ export function validateEmail(email) {
111
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
112
+ return emailRegex.test(email);
113
+ }
114
+ /**
115
+ * extract domain from the email.
116
+ *
117
+ * @param {string} email - The input email to extract domain.
118
+ */
119
+
120
+ export function extractDomainFromEmail(email) {
121
+ const atIndex = email.lastIndexOf('@');
122
+ return atIndex !== -1 ? email.slice(atIndex + 1) : '';
123
+ }
124
+ /**
125
+ * Reverse a given string.
126
+ *
127
+ * @param {string} string - The input string to reverse.
128
+ * @returns {string} The reversed string.
129
+ */
130
+
131
+ export function reverseString(string) {
132
+ return !isStringEmpty(string) ? string.split('').reverse().join('') : string;
133
+ }
134
+ /**
135
+ * Truncate a given string and append an ellipsis if it exceeds a specified length.
136
+ * @param {string} string - The string to truncate.
137
+ * @param {number} maxLength - The maximum length of the truncated string.
138
+ * @returns {string} The truncated string.
139
+ */
140
+
141
+ export function truncate(string) {
142
+ let maxLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
143
+
144
+ if (!isStringEmpty() && string.length > maxLength) {
145
+ return string.slice(0, maxLength) + '...';
146
+ }
147
+
148
+ return string;
149
+ }
150
+ /**
151
+ * Convert a string to PascalCase.
152
+ * Split the string into words, capitalize the first letter of each word, and join them
153
+ *
154
+ * @param {string} string - The input string to convert.
155
+ * @returns {string} The PascalCase version of the input string.
156
+ */
157
+
158
+ export function toPascalCase(string) {
159
+ if (typeof string === 'string' && !isStringEmpty(string)) {
160
+ const pascalCaseStr = string.split(/[\s_-]+/).map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join('');
161
+ return pascalCaseStr;
162
+ }
163
+ }
164
+ /**
165
+ * Convert a string to kebab-case.
166
+ * Replace spaces and underscores with hyphens, and convert to lowercase
167
+ *
168
+ * @param {string} string - The input string to convert.
169
+ * @returns {string} The kebab-case version of the input string.
170
+ */
171
+
172
+ export function toKebabCase(string) {
173
+ if (typeof string === 'string' && !isStringEmpty(string)) {
174
+ const kebabCaseStr = string.replace(/[\s_]+/g, '-').toLowerCase();
175
+ return kebabCaseStr;
176
+ }
177
+ }
178
+ /**
179
+ * Convert a string to snake_case.
180
+ * Replace spaces and hyphens with underscores, and convert to lowercase
181
+ *
182
+ * @param {string} string - The input string to convert.
183
+ * @returns {string} The snake_case version of the input string.
184
+ */
185
+
186
+ export function toSnakeCase(string) {
187
+ if (typeof string === 'string' && !isStringEmpty(string)) {
188
+ const snakeCaseStr = string.replace(/[\s-]+/g, '_').toLowerCase();
189
+ return snakeCaseStr;
190
+ }
191
+ }
192
+ /**
193
+ * Join an array of strings into a single string using a specified delimiter.
194
+ *
195
+ * @param {string[]} array - The array of strings to join.
196
+ * @param {string} delimiter - The delimiter used to separate the strings in the output.
197
+ * @returns {string} The concatenated string with the specified delimiter.
198
+ */
199
+
200
+ export function joinArray(array) {
201
+ let delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ', ';
202
+
203
+ if (Array.isArray(array)) {
204
+ return array.join(delimiter);
205
+ }
206
+ }
207
+ /**
208
+ * Remove whitespace characters from a given string.
209
+ *
210
+ * @param {string} inputString - The input string from which to remove whitespace.
211
+ * @returns {string} The input string with whitespace characters removed.
212
+ */
213
+
214
+ export function removeWhitespace(inputString) {
215
+ if (!isStringEmpty(inputString) && typeof inputString == 'string') {
216
+ return inputString.replace(/\s+/g, '');
217
+ }
218
+
219
+ return inputString;
220
+ }
221
+ /**
222
+ * Check if a given string is a palindrome.
223
+ *
224
+ * @param {string} string - The input string to check for palindromic property.
225
+ * @returns {boolean} True if the input string is a palindrome, false otherwise.
226
+ */
227
+
228
+ export function isPalindrome(string) {
229
+ if (!isStringEmpty(string) && typeof string == 'string') {
230
+ const cleanString = string.toLowerCase().replace(/[^a-zA-Z0-9]/g, '');
231
+ const reversedString = cleanString.split('').reverse().join('');
232
+ return cleanString === reversedString;
233
+ }
234
+
235
+ return string;
236
+ }
237
+ /**
238
+ * Check if a string starts with a vowel (a, e, i, o, or u).
239
+ *
240
+ * @param {string} string - The input string to check.
241
+ * @returns {boolean} True if the string starts with a vowel, false otherwise.
242
+ */
243
+
244
+ export function isStartsWithVowel(string) {
245
+ return /^[aeiouAEIOU]/.test(string);
246
+ }
247
+ ;
248
+ /**
249
+ * Count the number of occurrences of a substring in a string.
250
+ *
251
+ * @param {string} string - The input string to search in.
252
+ * @param {string} substring - The substring to count occurrences of.
253
+ * @returns {number} The number of occurrences of the substring in the input string.
254
+ */
255
+
256
+ export function countOccurrences(string, substring) {
257
+ if (typeof string == 'string') {
258
+ const regex = new RegExp(substring, 'g');
259
+ const matches = string.match(regex);
260
+ return matches ? matches.length : 0;
261
+ }
262
+
263
+ return string;
264
+ }
265
+ /**
266
+ * Replace all occurrences of a substring with another substring in a string.
267
+ *
268
+ * @param {string} string - The input string in which to perform replacements.
269
+ * @param {string} target - The substring to find and replace.
270
+ * @param {string} replacement - The substring to replace occurrences of the target with.
271
+ * @returns {string} The input string with all occurrences of the target replaced.
272
+ */
273
+
274
+ export function replaceAllOccurrences(string, target, replacement) {
275
+ if (!isStringEmpty(string) && typeof string == 'string') {
276
+ return string.split(target).join(replacement);
277
+ }
278
+
279
+ return string;
280
+ }
281
+ /**
282
+ * Encode a string to Base64.
283
+ *
284
+ * @param {string} inputString - The input string to encode.
285
+ * @returns {string} The Base64-encoded string.
286
+ */
287
+
288
+ export function encodeToBase64(string) {
289
+ return btoa(string);
290
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ *
3
+ * @param {number|string} count
4
+ * @param {object} options
5
+ * @param {string} options.locale
6
+ * @param {boolean} options.withAbbr
7
+ * @param {number} options.decimals
8
+ * @returns
9
+ */
10
+ export default function abbreviateNumber() {
11
+ let count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
12
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
13
+
14
+ if (typeof count === 'string') {
15
+ count = parseInt(count);
16
+ }
17
+
18
+ if (global.Intl && global.Intl.NumberFormat) {
19
+ let numberFormat = Intl.NumberFormat(options.locale || 'en', {
20
+ notation: 'compact' // compactDisplay: "short",
21
+
22
+ });
23
+ return numberFormat.format(count);
24
+ } //Comaptibility
25
+
26
+
27
+ const COUNT_ABBRS = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
28
+ let {
29
+ withAbbr = true,
30
+ decimals = 2
31
+ } = options;
32
+ const i = 0 === count ? count : Math.floor(Math.log(count) / Math.log(1000));
33
+ let result = parseFloat((count / Math.pow(1000, i)).toFixed(decimals));
34
+
35
+ if (withAbbr) {
36
+ result += `${COUNT_ABBRS[i]}`;
37
+ }
38
+
39
+ return result;
40
+ }
41
+ /* need discussion
42
+ 1001 => 1K+
43
+
44
+ G, T, P, E, Z,Y are needed in practical */
@@ -0,0 +1,18 @@
1
+ export default {
2
+ tab: 9,
3
+ enter: 13,
4
+ space: 32,
5
+ rightArrow: 39,
6
+ leftArrow: 37,
7
+ topArrow: 38,
8
+ bottomArrow: 40
9
+ };
10
+ export const accessKeyNames = {
11
+ 'tab': 'tab',
12
+ 'enter': 'enter',
13
+ 'space': 'space',
14
+ 'arrowleft': 'arrowleft',
15
+ 'arrowtop': 'arrowtop',
16
+ 'arrowright': 'arrowright',
17
+ 'arrowbottom': 'arrowbottom'
18
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Opening the customization, need to addd for behaviour changes. also add only enabled.
3
+ * @param {*} style
4
+ * @param {*} options
5
+ * Example code
6
+ * <Component openToCutsomize={{prefix:'dot'}} />
7
+ * let style = applyOpenToCustomize(style,openToCutsomize)
8
+ */
9
+ export default function applyOpenToCustomize(style, options) {
10
+ let resultStyle = style;
11
+
12
+ if (options && options.prefix) {
13
+ resultStyle = { ...style
14
+ };
15
+ let defaultPrefix = options.prefix || "";
16
+
17
+ if (defaultPrefix) {
18
+ defaultPrefix = `${defaultPrefix}-`;
19
+ }
20
+
21
+ Object.keys(style).forEach(styleName => {
22
+ if (resultStyle[styleName] && !resultStyle[styleName].includes(styleName)) {
23
+ resultStyle[styleName] = `${resultStyle[styleName]} ${defaultPrefix}${styleName}`;
24
+ }
25
+ });
26
+ }
27
+
28
+ return resultStyle;
29
+ }
@@ -0,0 +1,39 @@
1
+ const REPLACER_SYMBOL = "$";
2
+ /**
3
+ *
4
+ * if two is same ==> do the think if replace do, if append do.
5
+ * replace vs append ==> append
6
+ * append vs replace ==> replace
7
+ * @param {*} style1
8
+ * @param {*} style2
9
+ * @returns
10
+ */
11
+
12
+ export default function combineCustomStyle(style1, style2) {
13
+ let resultStyle = { ...style1
14
+ };
15
+ Object.keys(style2).forEach(styleName => {
16
+ let oldStyleName = style1[`$${styleName}`] ? `$${styleName}` : styleName;
17
+
18
+ if (oldStyleName.startsWith(REPLACER_SYMBOL) && styleName.startsWith(REPLACER_SYMBOL)) {
19
+ resultStyle[styleName] = style2[styleName];
20
+ } else if (!oldStyleName.startsWith(REPLACER_SYMBOL) && !styleName.startsWith(REPLACER_SYMBOL)) {
21
+ resultStyle[styleName] = `${resultStyle[styleName]} ${style2[styleName]}`;
22
+ } else {
23
+ delete resultStyle[oldStyleName];
24
+ resultStyle[styleName] = style2[styleName];
25
+ }
26
+ /*else if (oldStyleName.startsWith(REPLACER_SYMBOL) && !styleName.startsWith(REPLACER_SYMBOL) ) {
27
+
28
+ delete resultStyle[oldStyleName];
29
+ resultStyle[styleName] = style2[styleName];
30
+ }
31
+ else if (!oldStyleName.startsWith(REPLACER_SYMBOL) && styleName.startsWith(REPLACER_SYMBOL) ) {
32
+
33
+ delete resultStyle[oldStyleName];
34
+ resultStyle[styleName] = style2[styleName];
35
+ }*/
36
+
37
+ });
38
+ return resultStyle;
39
+ }
@@ -0,0 +1,29 @@
1
+ import dataTypes, { isDataTypeOf } from "./dataTypes";
2
+ import { hasOwnProperty } from "./objectUtils";
3
+
4
+ const collectClassNames = function (processedClassNameList) {
5
+ for (let index = 0; index < (arguments.length <= 1 ? 0 : arguments.length - 1); index++) {
6
+ let classInfo = index + 1 < 1 || arguments.length <= index + 1 ? undefined : arguments[index + 1];
7
+
8
+ if (!classInfo) {
9
+ continue;
10
+ } else if (isDataTypeOf(classInfo, dataTypes.object)) {
11
+ for (let property in classInfo) {
12
+ if (hasOwnProperty.call(classInfo, property) && property !== 'undefined' && property !== 'null' && classInfo[property] && !processedClassNameList.includes(property)) {
13
+ processedClassNameList.push(property);
14
+ }
15
+ }
16
+ }
17
+ }
18
+ };
19
+
20
+ export default function compileClassNames() {
21
+ let resultClassNameList = [];
22
+
23
+ for (var _len = arguments.length, classinfoList = new Array(_len), _key = 0; _key < _len; _key++) {
24
+ classinfoList[_key] = arguments[_key];
25
+ }
26
+
27
+ collectClassNames(resultClassNameList, ...classinfoList);
28
+ return resultClassNameList.filter(a => a !== '').join(' ');
29
+ }
@@ -0,0 +1,2 @@
1
+ export const DUMMY_OBJECT = Object.freeze({});
2
+ export const DUMMY_ARRAY = Object.freeze([]);
@@ -0,0 +1 @@
1
+ export * from "./uiProps";
@@ -0,0 +1,50 @@
1
+ export const variantList = {
2
+ outlined: 'variant_outlined',
3
+ contained: 'variant_contained',
4
+ flushed: 'variant_flushed',
5
+ plain: 'variant_plain'
6
+ };
7
+ export const variants = Object.values(variantList);
8
+ export const sizeList = {
9
+ xsmall: 'size_xsmall',
10
+ small: 'size_small',
11
+ medium: 'size_medium',
12
+ large: 'size_large',
13
+ xlarge: 'size_xlarge'
14
+ };
15
+ export const sizeKeys = Object.keys(sizeList);
16
+ export const sizes = Object.values(sizeList);
17
+ export const colorList = {
18
+ danger: 'color_danger',
19
+ success: 'color_success',
20
+ info: 'color_info',
21
+ primary: 'color_primary',
22
+ secondary: 'color_secondary',
23
+ warning: 'color_warning'
24
+ };
25
+ export const colorKeys = Object.keys(colorList);
26
+ export const colors = Object.values(colorList);
27
+ export const shapeList = {
28
+ circle: 'shape_circle',
29
+ oval: 'shape_oval',
30
+ square: 'shape_square',
31
+ roundedRect: 'shape_roundedRect',
32
+ rounded: 'shape_rounded'
33
+ };
34
+ export const shapes = Object.values(shapeList);
35
+ export const decorationList = {
36
+ overLine: 'decoration_overline',
37
+ lineThrough: 'decoration_linethrough',
38
+ underLine: 'decoration_underline',
39
+ none: 'decoration_none'
40
+ };
41
+ export const decorations = Object.values(decorationList);
42
+ export const positionList = {
43
+ left: 'position_left',
44
+ right: 'position_right',
45
+ top: 'position_top',
46
+ bottom: 'position_bottom',
47
+ center: 'position_center'
48
+ };
49
+ export const positionKeys = Object.keys(positionList);
50
+ export const positions = Object.values(positionList);
@@ -0,0 +1,15 @@
1
+ import { createContext } from 'react';
2
+ const context = {};
3
+ /**
4
+ *
5
+ * @param {string} name
6
+ * @returns {object}
7
+ */
8
+
9
+ export default function contextFactory(name) {
10
+ if (!context[name]) {
11
+ context[name] = /*#__PURE__*/createContext();
12
+ }
13
+
14
+ return context[name];
15
+ }
@@ -0,0 +1,77 @@
1
+ export default function createTemplateLiteral(templateStrings) {
2
+ for (var _len = arguments.length, expressionKeys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3
+ expressionKeys[_key - 1] = arguments[_key];
4
+ }
5
+
6
+ return function () {
7
+ for (var _len2 = arguments.length, expressionValues = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
8
+ expressionValues[_key2] = arguments[_key2];
9
+ }
10
+
11
+ let resultString = [templateStrings[0]];
12
+ expressionKeys.forEach(function (expressionKey, i) {
13
+ let expressionValue = expressionValues[i];
14
+ let nextTemplateString = templateStrings[i + 1];
15
+
16
+ if (expressionValue === null || expressionValue === undefined || expressionValue === "") {
17
+ nextTemplateString = nextTemplateString.replace(/^_/, '');
18
+ }
19
+
20
+ resultString.push(expressionValue, nextTemplateString);
21
+ });
22
+ let resultStr = resultString.join('');
23
+ resultStr = resultStr.replace(/_$/, '');
24
+ return resultStr;
25
+ };
26
+ }
27
+ /* refer the doc https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
28
+
29
+ UnderSatnd the terms - String interpolation, Embedded expressions
30
+
31
+ Go through the topic https://developers.google.com/web/updates/2015/01/ES6-Template-Strings#tagged_templates
32
+
33
+ Things to note fn`Hello ${you}! You're looking ${adjective} today!` desugars to fn(["Hello ", "! You're looking ", " today!"], you, adjective);
34
+
35
+ Please go through the example code
36
+
37
+ Our implementation constructCustomMessage is the handler for the tagged template function.
38
+ It receives the static words and its substitutions as seen above as the arguments.
39
+
40
+ It returns a function that receives the values for the substitutions. Upon passing the values for the inner function
41
+ it executes the algorithm as mentioned in the doc to construct the final message.
42
+ "The (n + 1)th argument corresponds to the substitution that takes place between the nth and (n + 1)th entries in the string array"
43
+
44
+
45
+ function constructCustomMessage(staticWordsList, ...embeddedExpressionKeyList)
46
+ {
47
+ return (...valuesForEmbeddedExpressionList)=>{
48
+
49
+ let finalMessage = staticWordsList[0];
50
+ embeddedExpressionKeyList.forEach(function(expressionKey, index) {
51
+ let expressionValue = valuesForEmbeddedExpressionList[index];
52
+ let nextStaticWord = staticWordsList[index+1];
53
+ if(expressionValue===null || expressionValue === undefined || expressionValue === ""){
54
+ // Replace the underscore '_' present at the beginning of string with empty value.
55
+ nextStaticWord = nextStaticWord.replace(/^_/, '');
56
+ }
57
+ finalMessage += expressionValue + nextStaticWord;
58
+
59
+ });
60
+ // Replace the underscore '_' present at the end of string with empty value.
61
+ finalMessage = finalMessage.replace(/_$/,'');
62
+ return finalMessage ;
63
+ };
64
+
65
+ }
66
+ */
67
+
68
+ /*
69
+ Sample Invocation Format
70
+
71
+ var username;
72
+ var tag;
73
+ var handlerFunctiontoFormMessage = constructCustomMessage`<b>${username} says</b>: "${tag}"`;
74
+ var outputString = handlerFunctiontoFormMessage('Mani Venkat', '& is a fun tag');
75
+ console.log(outputString);
76
+
77
+ */