@controlium/utils 1.0.2-alpha.2 → 1.0.2-alpha.3

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.
@@ -1,294 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StringUtils = void 0;
4
- const index_1 = require("../index");
5
- const utils_1 = require("../utils/utils");
6
- /**
7
- * General String related test-related utilities.
8
- * @note
9
- * Originally written as String extensions, re-written as static functions for broader compatibility.
10
- */
11
- class StringUtils {
12
- /**
13
- * Removes leading and trailing instances of given character from a string
14
- * @param originalString
15
- * String to be trimmed
16
- * @param characterToTrim
17
- * Character to be removed from start and end of string, if present
18
- */
19
- static trimChar(originalString, characterToTrim) {
20
- utils_1.Utils.assertType(originalString, "string", "trimChar", "originalString");
21
- utils_1.Utils.assertType(characterToTrim, "string", "trimChar", "characterToTrim");
22
- // Check we have only been given a single char to trim. Bomb if not.
23
- if (characterToTrim.length !== 1) {
24
- const error = `characterToTrim (${characterToTrim}) must be a single character!`;
25
- index_1.Log.writeLine(index_1.LogLevels.Error, ` ${error}`);
26
- throw new Error(error);
27
- }
28
- let normalizedCharToTrim = characterToTrim === "]" ? "\\]" : characterToTrim;
29
- normalizedCharToTrim = normalizedCharToTrim === "^" ? "\\^" : normalizedCharToTrim;
30
- normalizedCharToTrim = normalizedCharToTrim === "\\" ? "\\\\" : normalizedCharToTrim;
31
- return originalString.replace(new RegExp("^[" + normalizedCharToTrim + "]+|[" + normalizedCharToTrim + "]+$", "g"), "");
32
- }
33
- /**
34
- * Trims single or double quotes from string if string starts AND ends in same quote character
35
- * @param originalString
36
- * String to be trimmed
37
- */
38
- static trimQuotes(originalString) {
39
- utils_1.Utils.assertType(originalString, "string", "trimQuotes", "originalString");
40
- let trimmedString = originalString;
41
- if ((trimmedString.startsWith("'") && trimmedString.endsWith("'")) || (trimmedString.startsWith('"') && trimmedString.endsWith('"'))) {
42
- trimmedString = trimmedString.substring(1, trimmedString.length - 1);
43
- }
44
- return trimmedString;
45
- }
46
- /**
47
- * Checks if character at index is an Alpha character
48
- * @param stringToCheck
49
- * String containing character to check
50
- * @param indexZeroBased - default 0
51
- * Index of character to check
52
- * @returns
53
- * Boolean true is alpha, otherwise false
54
- */
55
- static isAlpha(stringToCheck, indexZeroBased = 0) {
56
- utils_1.Utils.assertType(stringToCheck, "string", "isAlpha", "stringToCheck");
57
- utils_1.Utils.assertType(indexZeroBased, "number", "isAlpha", "indexZeroBased");
58
- if (stringToCheck.length - 1 < indexZeroBased) {
59
- const errorText = `Cannot check if char [${indexZeroBased} (Zero based)] isAlpha as length of stringToCheck is only ${stringToCheck.length} characters long!`;
60
- index_1.Log.writeLine(index_1.LogLevels.Error, errorText);
61
- throw new Error(errorText);
62
- }
63
- return stringToCheck.charAt(indexZeroBased).toLowerCase() !== stringToCheck.charAt(indexZeroBased).toUpperCase();
64
- }
65
- /**
66
- * Set first character of string to Capital (if Alpha)
67
- * @param originalString
68
- * String to set first character
69
- * @returns
70
- * originalString with first character capitalised
71
- */
72
- static capitaliseFirstCharacter(originalString, searchFirstAlpha = false) {
73
- utils_1.Utils.assertType(originalString, "string", "capitaliseFirstCharacter", "originalString");
74
- if (searchFirstAlpha) {
75
- const asArray = originalString.split("");
76
- asArray.find((item, index) => {
77
- if (this.isAlpha(item)) {
78
- asArray[index] = item.toUpperCase();
79
- return true;
80
- }
81
- else {
82
- return false;
83
- }
84
- });
85
- return asArray.join("");
86
- }
87
- else {
88
- return originalString.charAt(0).toUpperCase() + originalString.slice(1);
89
- }
90
- }
91
- /**
92
- * Splits a string upto substrings a maximum number of times using the specified separator and return then as an array
93
- * @param originalString
94
- * String to be split
95
- * @param separator
96
- * Character to use as seperator. If more than one character, function will error.
97
- * @param limit
98
- * A value used to limit the number of elements returned in the array. Last element contains rest of string.
99
- */
100
- static splitRemaining(originalString, separator, limit, doNotSeparateInQuotes = false) {
101
- utils_1.Utils.assertType(originalString, "string", "splitRemaining", "originalString");
102
- utils_1.Utils.assertType(separator, "string", "splitRemaining", "separator");
103
- utils_1.Utils.assertType(limit, "number", "splitRemaining", "limit");
104
- if (separator.length === 1 && limit > 0) {
105
- const allParts = StringUtils.split(originalString, separator, doNotSeparateInQuotes);
106
- const partsToMax = allParts.slice(0, limit - 1);
107
- const partsAfterMax = allParts.slice(limit - 1);
108
- return partsAfterMax.length > 0 ? partsToMax.concat([partsAfterMax.join(separator)]) : partsToMax;
109
- }
110
- else {
111
- const error = `Seperator [Length was ${separator.length}] must be single character and limit [Limit was ${limit}] greater than 0.`;
112
- index_1.Log.writeLine(index_1.LogLevels.Error, error);
113
- throw new Error(error);
114
- }
115
- }
116
- /**
117
- * Splits a string upto substrings a maximum number of times using the specified separator and return then as an array
118
- * @param originalString
119
- * String to be split
120
- * @param separator
121
- * A string that identifies character or characters to use in separating the string.
122
- * @param limit
123
- * A value used to limit the number of elements returned in the array. First element contains start of string.
124
- */
125
- static splitLeading(originalString, separator, limit, doNotSeparateInQuotes = false) {
126
- utils_1.Utils.assertType(originalString, "string", "splitLeading", "originalString");
127
- utils_1.Utils.assertType(separator, "string", "splitLeading", "separator");
128
- utils_1.Utils.assertType(limit, "number", "splitLeading", "limit");
129
- const realLimit = limit > originalString.length ? originalString.length : limit;
130
- if (separator.length === 1 && limit > 0) {
131
- const allParts = StringUtils.split(originalString, separator, doNotSeparateInQuotes);
132
- const partsToMax = allParts.slice(0, allParts.length - realLimit + 1);
133
- const partsAfterMax = allParts.slice(allParts.length - realLimit + 1, allParts.length);
134
- return partsToMax.length > 0 ? [partsToMax.join(separator)].concat(partsAfterMax) : partsAfterMax;
135
- }
136
- else {
137
- const error = `Seperator [Length was ${separator.length}] must be single character and limit [Limit was ${limit}] greater than 0.`;
138
- index_1.Log.writeLine(index_1.LogLevels.Error, error);
139
- throw new Error(error);
140
- }
141
- }
142
- /**
143
- * Splits a string into parts, optionally ignoring slips with quotes
144
- * @param originalString
145
- * String to be split
146
- * @param separator
147
- * Character to use as seperator. If more than one character, function will error.
148
- * @param doNotSeparateInQuotes (default true)
149
- * If true, separator char is ignored within single or double quotes (matching)
150
- * @returns
151
- * Array of original string
152
- */
153
- static split(originalString, separator, doNotSeparateInQuotes = true) {
154
- utils_1.Utils.assertType(originalString, "string", "split", "originalString");
155
- utils_1.Utils.assertType(separator, "string", "split", "separator");
156
- if (separator.length === 1) {
157
- if (doNotSeparateInQuotes) {
158
- const result = originalString.match(/\\?.|^$/g)?.reduce((workingObject, currentChar) => {
159
- if (['"', "'"].includes(currentChar)) {
160
- if (workingObject.inQuote === "") {
161
- workingObject.inQuote = currentChar;
162
- }
163
- else if (workingObject.inQuote === currentChar) {
164
- workingObject.inQuote = "";
165
- }
166
- }
167
- if (workingObject.inQuote === "" && currentChar === separator) {
168
- workingObject.array[workingObject.array.length - 1] = StringUtils.trimQuotes(workingObject.array[workingObject.array.length - 1]);
169
- workingObject.array.push("");
170
- }
171
- else {
172
- workingObject.array[workingObject.array.length - 1] += currentChar.replace(/\\(.)/, "$1");
173
- }
174
- return workingObject;
175
- }, { array: [""], inQuote: "" }).array ?? [originalString];
176
- result[result.length - 1] = StringUtils.trimQuotes(result[result.length - 1]);
177
- return result;
178
- }
179
- else {
180
- return originalString.split(separator);
181
- }
182
- }
183
- else {
184
- const error = `Seperator [Length was ${separator.length}] must be single character.`;
185
- index_1.Log.writeLine(index_1.LogLevels.Error, error);
186
- throw new Error(error);
187
- }
188
- }
189
- /**
190
- * Splits a string into verb and paremeters. Parameters are part enclosed in trailing brackets.
191
- * @param rawCommand
192
- * String containing command verb and, optionally, braces enclosing parameters
193
- * @returns
194
- * Object with verb and parameters properties
195
- * @example
196
- * "hello"
197
- * results in verb: "hello", parameters: ''
198
- * "hello(this is, good)"
199
- * results in verb: "hello", parameters: 'this is, good'
200
- * @throws
201
- * Error if badly formed (no trailing close braces etc....)
202
- */
203
- static splitVerbAndParameters(rawCommand) {
204
- index_1.Log.writeLine(index_1.LogLevels.FrameworkDebug, `Got string [${rawCommand}]`);
205
- if (rawCommand.includes("(")) {
206
- if (rawCommand.endsWith(")")) {
207
- let paramsPart = StringUtils.splitRemaining(rawCommand, '(', 2)[1];
208
- paramsPart = paramsPart.substring(0, paramsPart.length - 1);
209
- index_1.Log.writeLine(index_1.LogLevels.FrameworkDebug, `Parameters are: [${paramsPart}]`);
210
- return {
211
- verb: rawCommand.split("(")[0],
212
- parameters: paramsPart,
213
- };
214
- }
215
- else {
216
- const errText = `Object <${rawCommand}> has no closing brackets! If has opening brackets then must have closing brackets`;
217
- index_1.Log.writeLine(index_1.LogLevels.Error, errText);
218
- throw new Error(errText);
219
- }
220
- }
221
- else {
222
- return {
223
- verb: rawCommand,
224
- parameters: "",
225
- };
226
- }
227
- }
228
- /**
229
- * Removes all non-alphanumerics from string
230
- * @param originalString
231
- * String to remove non-alphanumerics from
232
- */
233
- static removeNonAlphaNumeric(originalString) {
234
- utils_1.Utils.assertType(originalString, "string", "removeNonAlphaNumeric", "originalString");
235
- return originalString.replace(/[^a-zA-Z0-9]+/g, "");
236
- }
237
- /**
238
- * Removes all whitespace from string
239
- * @param originalString
240
- * String to remove whitespace from
241
- */
242
- static removeWhitespace(originalString) {
243
- utils_1.Utils.assertType(originalString, "string", "removeWhitespace", "originalString");
244
- return originalString.replace(/\s+/g, "");
245
- }
246
- /**
247
- * Encode given string to enable use within HTML
248
- * @param originalString
249
- * Non-encoded string to be HTML encoded
250
- * @returns
251
- * Original string HTML encoded.
252
- */
253
- static encodeHTML(originalString) {
254
- utils_1.Utils.assertType(originalString, "string", "encodeHTML", "originalString");
255
- return originalString.replace(/[&<>'"]/g, (tag) => ({
256
- "&": "&amp;",
257
- "<": "&lt;",
258
- ">": "&gt;",
259
- "'": "&#39;",
260
- '"': "&quot;",
261
- }[tag] ?? ""));
262
- }
263
- /**
264
- * Replace all matching instances with replacement
265
- * @param original
266
- * String to replace values in
267
- * @param searchValue
268
- * Value to replace
269
- * @param replaceValue
270
- * Value to replace mathes with
271
- * @returns
272
- * Original string with all matching occuranced replaced
273
- */
274
- static replaceAll(original, searchValue, replaceValue) {
275
- if (utils_1.Utils.isNullOrUndefined(original)) {
276
- const errText = `Cannot replace [${searchValue}] with [${replaceValue}] Original is null or undefined!`;
277
- index_1.Log.writeLine(index_1.LogLevels.Error, errText);
278
- throw new Error(errText);
279
- }
280
- const escapedRegExp = new RegExp(index_1.JsonUtils.escapeRegExp(searchValue), 'g');
281
- return original.replace(escapedRegExp, replaceValue);
282
- }
283
- /**
284
- * Checks if a string is blank
285
- * @param text
286
- * String to be verified for blank
287
- * @returns
288
- * Boolean true is empty or with blankspaces, otherwise false
289
- */
290
- static isBlank(text) {
291
- return utils_1.Utils.isNullOrUndefined(text) || text.trim().length === 0;
292
- }
293
- }
294
- exports.StringUtils = StringUtils;