qsu 0.3.5 → 0.5.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.
package/README.md CHANGED
@@ -76,22 +76,28 @@ Utility to help process array type data.
76
76
  | .setWithDefault | <li>defaultValue **{Any}**</li><li>arrayLength **{Number&#124;null}**</li> | Initialize an array with a default value of a specific length. | `setWithDefault('abc', 4) // ['abc', 'abc', 'abc', 'abc']`<br/>`setWithDefault(null, 3) // [null, null, null]` |
77
77
  | .unique | array **{Array}** | Remove duplicate values from array and two-dimensional array data. In the case of 2d arrays, json type data duplication is not removed. | `unique([1, 2, 2, 3]) // [1, 2, 3]`<br/>`unique([[1], [1], [2]) // [[1], [2]]` |
78
78
  | .setWithNumber | <li>start **{Number}**</li><li>end **{Number}**</li> | Creates and returns an Array in the order of start...end values. | `setWithNumber(1, 3) // [1, 2, 3]`<br/>`setWithNumber(0, 3) // [0, 1, 2, 3]` |
79
+ | .average | <li>array **{Array}**</li> | Returns the average of all numeric values in an array. | `average([1, 5, 15, 50]) // 17.75` |
79
80
 
80
81
  ## qsu.string
81
82
  Utility to help process string type data.
82
83
 
83
- | Method | Params | Description | Example |
84
- | --- | --- | --- | --- |
85
- | .removeSpecialChar | string **{String}** | Returns after removing all special characters, including spaces. | `removeSpecialChar('Hello, World!') // 'HelloWorld'` |
86
- | .removeNewLine | string **{String}** | Removes \n, \r characters or replaces them with specified characters. | `removeNewLine('ab\ncd') // 'abcd'`<br/>`removeNewLine('ab\r\ncd', '-') // 'ab-cd'` |
87
- | .capitalizeFirst | string **{String}** | Converts the first letter of the entire string to uppercase and returns. | `capitalizeFirst('abcd') // 'Abcd'` |
88
- | .count | <li>string **{String}**</li><li>search **{String}**</li> | Returns the number of times the second String character is contained in the first String argument. | `count('abcabc', 'a') // 2` |
89
- | .shuffle | <li>string **{String}**</li> | Randomly shuffles the received string and returns it. | `shuffle('abcdefg') // 'bgafced'` |
90
- | .createRandom | <li>length **{Number}**</li> | Returns a random String containing numbers or uppercase and lowercase letters of the given length. The default return length is 12. | `createRandom(5) // 'CHy2M'` |
91
- | .hideRandom | <li>str **{String}**</li><li>hideLength **{Number}**</li><li>hideStr **{String}**</li> | Replaces strings at random locations with a specified number of characters (default 1) with characters (default *). | `hideRandom('hello', 2, '#') // '#el#o'` |
92
- | .truncate | <li>str **{String}**</li><li>length **{Number}**</li><li>ellipsis **{String&#124;null}**</li> | Truncates a long string to a specified length, optionally appending an ellipsis after the string. | `truncate('hello', 3) // 'hel'`<br/>`truncate('hello', 2, '...') // 'he...'` |
93
- | .encrypt | <li>str **{String}**</li><li>secret **{String}**</li><li>algorithm **{String&#124;null}**</li> | Encrypt with the algorithm of your choice (default: aes-256-cbc) using a string and a secret (secret). | `encrypt('test', 'secret-key')` |
94
- | .decrypt | <li>str **{String}**</li><li>secret **{String}**</li><li>algorithm **{String&#124;null}**</li> | Decrypt with the specified algorithm (default: `aes-256-cbc`) using a string and a secret (secret). | `decrypt('61ba43b65fc...', 'secret-key') // 'test'` |
84
+ | Method | Params | Description | Example |
85
+ | --- |--------------------------------------------------------------------------------------------------------------------------------------| --- |----------------------------------------------------------------------------------------|
86
+ | .removeSpecialChar | <li>string **{String}**</li><li>withoutSpace **{Boolean}**</li> | Returns after removing all special characters, including spaces. | `removeSpecialChar('Hello, World!') // 'HelloWorld'` |
87
+ | .removeNewLine | string **{String}** | Removes \n, \r characters or replaces them with specified characters. | `removeNewLine('ab\ncd') // 'abcd'`<br/>`removeNewLine('ab\r\ncd', '-') // 'ab-cd'` |
88
+ | .capitalizeFirst | string **{String}** | Converts the first letter of the entire string to uppercase and returns. | `capitalizeFirst('abcd') // 'Abcd'` |
89
+ | .capitalizeEachWords | <li>string **{String}**</li><li>naturally **{Boolean}**</li> | Converts every word with spaces to uppercase. If the naturally argument is true, only some special cases (such as prepositions) are kept lowercase. | `capitalizeEachWords('hello world') // 'Hello World'` |
90
+ | .count | <li>string **{String}**</li><li>search **{String}**</li> | Returns the number of times the second String character is contained in the first String argument. | `count('abcabc', 'a') // 2` |
91
+ | .shuffle | <li>string **{String}**</li> | Randomly shuffles the received string and returns it. | `shuffle('abcdefg') // 'bgafced'` |
92
+ | .createRandom | <li>length **{Number}**</li> | Returns a random String containing numbers or uppercase and lowercase letters of the given length. The default return length is 12. | `createRandom(5) // 'CHy2M'` |
93
+ | .hideRandom | <li>str **{String}**</li><li>hideLength **{Number}**</li><li>hideStr **{String}**</li> | Replaces strings at random locations with a specified number of characters (default 1) with characters (default *). | `hideRandom('hello', 2, '#') // '#el#o'` |
94
+ | .truncate | <li>str **{String}**</li><li>length **{Number}**</li><li>ellipsis **{String&#124;null}**</li> | Truncates a long string to a specified length, optionally appending an ellipsis after the string. | `truncate('hello', 3) // 'hel'`<br/>`truncate('hello', 2, '...') // 'he...'` |
95
+ | .encrypt | <li>str **{String}**</li><li>secret **{String}**</li><li>algorithm **{String&#124;null}**</li><li>ivSize **{Number&#124;null}**</li> | Encrypt with the algorithm of your choice (algorithm default: aes-256-cbc, ivSize default: 16) using a string and a secret (secret). | `encrypt('test', 'secret-key')` |
96
+ | .decrypt | <li>str **{String}**</li><li>secret **{String}**</li><li>algorithm **{String&#124;null}**</li> | Decrypt with the specified algorithm (default: `aes-256-cbc`) using a string and a secret (secret). | `decrypt('61ba43b65fc...', 'secret-key') // 'test'` |
97
+ | .md5 | <li>str **{String}**</li> | Converts String data to md5 hash value and returns it. | `md5('test') // '098f6bcd4621d373cade4e832627b4f6'` |
98
+ | .sha1 | <li>str **{String}**</li> | Converts String data to sha1 hash value and returns it. | `sha1('test') // 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'` |
99
+ | .sha256 | <li>str **{String}**</li> | Converts String data to sha256 hash value and returns it. | `sha256('test') // '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'` |
100
+ | .unique | <li>str **{String}**</li> | Remove duplicate characters from a given string and output only one. | `unique('aaabbbcc') // 'abc'` |
95
101
 
96
102
  ## qsu.math
97
103
  Utility for arithmetic on numbers.
@@ -105,15 +111,15 @@ Utility for arithmetic on numbers.
105
111
  ## qsu.verify
106
112
  Utility for data inspection.
107
113
 
108
- | Method | Params | Description | Example |
109
- | --- | --- | --- | --- |
110
- | .empty | data **{Any}** | Returns true if the passed data is empty or has a length of 0. | `empty([]) // true`<br/>`empty('') // true`<br/>`empty('abc') // false` |
111
- | .isUrl | <li>url **{String}**</li><li>withProtocol **{Boolean&#124;null}**</li><li>strict **{Boolean&#124;null}**</li> | Returns true if the given data is in the correct URL format. If withProtocol is true, it is automatically appended to the URL when the protocol does not exist. If strict is true, URLs without commas (.) return false. | `isUrl('google.com') // false`<br/>`isUrl('google.com', true) // true`<br/>`isUrl('https://google.com') // true` |
112
- | .contains | <li>string **{String}**</li><li>searchData **{Array&#124;String}** | Returns true if the first string argument contains the second argument "string" or "one or more of the strings listed in the array". | `contains('abc', 'a') // true`<br/>`contains('abc', 'd') // false`<br/>`contains('abc', ['a', 'd']) // true` |
113
- | .is2dArray | array **{Array}** | Returns true if the given array is a two-dimensional array. | `is2dArray([1]) // false`<br/>`is2dArray([[1], [2]) // true` |
114
- | .between | <li>value **{Number}**</li><li>range **{[min, max]}</li><li>inclusive **{Boolean&#124;null}**</li>** | Returns true if the first argument is in the range of the second argument ([min, max]). To allow the minimum and maximum values to be in the range, pass true for the third argument. | `between(10, [10, 20]) // false`<br/>`between(10, [10, 20], true) // true` |
115
- | .length | <li>data **{Any}**</li> | Returns the length of any type of data. If the argument value is null or undefined, 0 is returned. | `length('12345') // 5`<br/>`length([1, 2, 3]]) // 3` |
116
- | .isBotAgent | <li>userAgent **{String}**</li> | Analyze the user agent value to determine if it's a bot for a search engine. Returns true if it's a bot. | `isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)') // true` |
114
+ | Method | Params | Description | Example |
115
+ | --- |-----------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| --- |
116
+ | .empty | data **{Any}** | Returns true if the passed data is empty or has a length of 0. | `empty([]) // true`<br/>`empty('') // true`<br/>`empty('abc') // false` |
117
+ | .isUrl | <li>url **{String}**</li><li>withProtocol **{Boolean&#124;null}**</li><li>strict **{Boolean&#124;null}**</li> | Returns true if the given data is in the correct URL format. If withProtocol is true, it is automatically appended to the URL when the protocol does not exist. If strict is true, URLs without commas (.) return false. | `isUrl('google.com') // false`<br/>`isUrl('google.com', true) // true`<br/>`isUrl('https://google.com') // true` |
118
+ | .contains | <li>string **{String}**</li><li>searchData **{Array&#124;String}**</li><li>exact **{Boolean}**</li> | Returns true if the first string argument contains the second argument "string" or "one or more of the strings listed in the array". If the exact value is true, it returns true only for an exact match. | `contains('abc', 'a') // true`<br/>`contains('abc', 'd') // false`<br/>`contains('abc', ['a', 'd']) // true` |
119
+ | .is2dArray | array **{Array}** | Returns true if the given array is a two-dimensional array. | `is2dArray([1]) // false`<br/>`is2dArray([[1], [2]) // true` |
120
+ | .between | <li>value **{Number}**</li><li>range **{[min, max]}</li><li>inclusive **{Boolean&#124;null}**</li>** | Returns true if the first argument is in the range of the second argument ([min, max]). To allow the minimum and maximum values to be in the range, pass true for the third argument. | `between(10, [10, 20]) // false`<br/>`between(10, [10, 20], true) // true` |
121
+ | .length | <li>data **{Any}**</li> | Returns the length of any type of data. If the argument value is null or undefined, 0 is returned. | `length('12345') // 5`<br/>`length([1, 2, 3]]) // 3` |
122
+ | .isBotAgent | <li>userAgent **{String}**</li> | Analyze the user agent value to determine if it's a bot for a search engine. Returns true if it's a bot. | `isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)') // true` |
117
123
 
118
124
  ## qsu.format
119
125
  Utility that converts to Human-Readable String format.
@@ -121,10 +127,12 @@ Utility that converts to Human-Readable String format.
121
127
  | Method | Params | Description | Example |
122
128
  | --- | --- | --- | --- |
123
129
  | .number | val **{String&#124;Number}** | Return in number format including comma symbol. | `number(1234567) // 1,234,567` |
130
+ | .fileName | <li>filePath **{String}**</li><li>withExtension **{Boolean}**</li> | Extract the file name from the path. Include the extension if withExtension is true. | `fileName('C:\Temp\hello.txt') // 'hello.txt'`<br/>`fileName('C:\Temp\file.mp3', true) // 'file.mp3'` |
124
131
  | .fileSize | <li>bytes **{Number}**</li><li>decimals **{Number}**</li> | Converts the file size in bytes to human-readable and returns it. The return value is a String and includes the file units (Bytes, MB, GB...). If the second optional argument value is included, you can display as many decimal places as you like. | `fileSize(2000, 3) // '1.953 KB'`<br/>`fileSize(250000000) // '238.42 MB'` |
125
- | .fileExt | <li>path **{String}**</li> | Returns only the extensions in the file path. If unknown, returns 'Unknown'. | `fileExt('C:\Temp\hello.txt') // 'txt'`<br/>`fileExt('this-is-file.mp3') // 'mp3'` |
132
+ | .fileExt | <li>filePath **{String}**</li> | Returns only the extensions in the file path. If unknown, returns 'Unknown'. | `fileExt('C:\Temp\hello.txt') // 'txt'`<br/>`fileExt('this-is-file.mp3') // 'mp3'` |
126
133
  | .msToTime | <li>milliseconds **{Number}**</li><li>withMilliseconds **{Boolean}**</li><li>separator **{String}**</li> | Converts milliseconds to hours, minutes, seconds, and milliseconds and returns. If the second argument is true, milliseconds are also printed. You can put any separator (String) between hours, minutes, and seconds in the third argument. | `msToTime(100000) // '00:01:40'`<br/>`msToTime(100000, true, '-') // '00-01-40.0'` |
127
134
  | .secToTime | <li>seconds **{Number}**</li><li>separator **{String}**</li><li>onlyHour **{Boolean}**</li> | Converts seconds to hours, minutes, seconds and returns. You can put any separator (String) between hours, minutes, and seconds in the third argument. | `secToTime(3800) // '01:03:20'`<br/>`secToTime(60, '-') // '00-01-00'` |
135
+ | .license | <li>type(Required, Currently only 'mit' is supported) **{String}**</li><li>author(Required) **{String}**</li><li>yearStart(Required) **{String}**</li><li>yearEnd **{String}**</li><li>email **{string}**</li><li>htmlBr **{string}**</li> | Returns text in a specific license format based on the author information of the given argument. The argument uses the Object type. | `license({ holder: 'example', email: 'example@example.com', yearStart: 2020, yearEnd: 2021, htmlBr: true })` |
128
136
 
129
137
  ## qsu.date
130
138
  Utility to simplify date format printing or calculation.
package/array.js CHANGED
@@ -33,9 +33,15 @@ const setWithNumber = (start, end) => {
33
33
  return Array.from({ length: (end - start) + 1 }, (_, i) => i + start);
34
34
  };
35
35
 
36
+ const average = (arr) => {
37
+ if (!arr) return null;
38
+ return arr.reduce((p, c) => p + c, 0) / arr.length;
39
+ };
40
+
36
41
  module.exports = {
37
42
  shuffle,
38
43
  setWithDefault,
39
44
  unique,
40
45
  setWithNumber,
46
+ average,
41
47
  };
package/format.js CHANGED
@@ -1,5 +1,17 @@
1
+ const path = require('path');
2
+
1
3
  const number = (v) => new Intl.NumberFormat().format(v);
2
4
 
5
+ const fileName = (filePath, withExtension) => {
6
+ if (!filePath || typeof filePath !== 'string' || filePath.length < 1) {
7
+ throw new Error('Unknown file path');
8
+ }
9
+ if (withExtension) {
10
+ return path.basename(filePath);
11
+ }
12
+ return path.basename(filePath, path.extname(filePath));
13
+ };
14
+
3
15
  const fileSize = (bytes, decimals = 2) => {
4
16
  if (bytes === null || typeof bytes !== 'number' || typeof decimals !== 'number') return 'Unknown';
5
17
  if (bytes === 0 || bytes < 0) return '0 Bytes';
@@ -7,9 +19,9 @@ const fileSize = (bytes, decimals = 2) => {
7
19
  return `${parseFloat((bytes / 1024 ** byteCalc).toFixed((decimals < 0 ? 0 : decimals)))} ${['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][byteCalc]}`;
8
20
  };
9
21
 
10
- const fileExt = (path) => {
11
- if (!path || typeof path !== 'string' || path.indexOf('.') === -1) return 'Unknown';
12
- const p = path.trim().toLowerCase();
22
+ const fileExt = (filePath) => {
23
+ if (!filePath || typeof filePath !== 'string' || filePath.indexOf('.') === -1) return 'Unknown';
24
+ const p = filePath.trim().toLowerCase();
13
25
  const pSpl = p.split('.');
14
26
  return pSpl.length > 0 ? pSpl[pSpl.length - 1] : 'Unknown';
15
27
  };
@@ -37,10 +49,28 @@ const secToTime = (seconds = 0, separator = ':', onlyHour = false) => {
37
49
  return onlyHour ? hour : `${hour}${separator}${min}${separator}${sec}`;
38
50
  };
39
51
 
52
+ const license = (args = {}) => {
53
+ if (typeof args !== 'object' || args.length < 1) {
54
+ throw new Error('An argument of type Object is required. Please refer to README.md.');
55
+ }
56
+ if (!args.author || !args.yearStart) {
57
+ throw new Error('holder and startYear are required.');
58
+ }
59
+ const br = args.htmlBr ? '<br/>' : '\n';
60
+ const type = args?.type?.toLowerCase() || 'mit';
61
+ switch (type) {
62
+ case 'mit':
63
+ default:
64
+ return `Copyright (c) ${args.yearStart}${args.yearEnd ? `-${args.yearEnd}` : ''} ${args.author}${args.email ? ` <${args.email}>` : ''}${br}${br}Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:${br}${br}The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.${br}${br}THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`;
65
+ }
66
+ };
67
+
40
68
  module.exports = {
41
69
  number,
70
+ fileName,
42
71
  fileSize,
43
72
  fileExt,
44
73
  msToTime,
45
74
  secToTime,
75
+ license,
46
76
  };
package/misc.js CHANGED
@@ -2,11 +2,6 @@ const sleep = (delay = 0) => new Promise((resolve) => {
2
2
  setTimeout(resolve, delay);
3
3
  });
4
4
 
5
- const nothing = (args) => {
6
- if (args && typeof args === 'function') { args(); }
7
- };
8
-
9
5
  module.exports = {
10
6
  sleep,
11
- nothing,
12
7
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qsu",
3
- "version": "0.3.5",
3
+ "version": "0.5.1",
4
4
  "description": "Quick and Simple Utility for javascript",
5
5
  "scripts": {
6
6
  "test": "npm run lint && mocha --require @babel/register --parallel test/*.spec.js",
@@ -18,13 +18,13 @@
18
18
  "url": "https://github.com/jooy2/qsu"
19
19
  },
20
20
  "devDependencies": {
21
- "@babel/node": "^7.15.4",
22
- "@babel/preset-env": "^7.15.4",
23
- "@babel/register": "^7.15.3",
24
- "eslint": "^7.32.0",
25
- "eslint-config-airbnb": "^18.2.1",
26
- "eslint-plugin-import": "^2.24.2",
27
- "mocha": "^9.1.1"
21
+ "@babel/node": "^7.16.0",
22
+ "@babel/preset-env": "^7.16.4",
23
+ "@babel/register": "^7.16.0",
24
+ "eslint": "^8.4.1",
25
+ "eslint-config-airbnb": "^19.0.2",
26
+ "eslint-plugin-import": "^2.25.3",
27
+ "mocha": "^9.1.3"
28
28
  },
29
29
  "dependencies": {
30
30
  "moment": "^2.29.1"
package/string.js CHANGED
@@ -1,9 +1,10 @@
1
1
  const crypto = require('crypto');
2
2
  const { rand } = require('./math');
3
+ const { contains } = require('./verify');
3
4
 
4
- const removeSpecialChar = (str) => {
5
+ const removeSpecialChar = (str, withoutSpace) => {
5
6
  if (!str || typeof str !== 'string') return str;
6
- return str.replace(/[^a-zA-Z가-힣ㄱ-ㅎㅏ-ㅣ0-9\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/gi, '');
7
+ return str.replace(new RegExp(`[^a-zA-Z가-힣ㄱ-ㅎㅏ-ㅣ0-9\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f${withoutSpace ? ' ' : ''}]`, 'gi'), '');
7
8
  };
8
9
 
9
10
  const removeNewLine = (str, replaceTo = '') => {
@@ -16,6 +17,20 @@ const capitalizeFirst = (str) => {
16
17
  return str.charAt(0).toUpperCase() + str.slice(1);
17
18
  };
18
19
 
20
+ const capitalizeEachWords = (str, naturally) => {
21
+ if (!str || typeof str !== 'string' || str.length < 1) return null;
22
+ const splitStr = str.trim().toLowerCase().split(' ');
23
+ for (let i = 0, iLen = splitStr.length; i < iLen; i += 1) {
24
+ if (!naturally || !contains(splitStr[i], [
25
+ 'in', 'on', 'the', 'at', 'and', 'or', 'of', 'for', 'to', 'that',
26
+ 'a', 'by', 'it', 'is', 'as', 'are', 'were', 'was', 'nor', 'an',
27
+ ])) {
28
+ splitStr[i] = capitalizeFirst(splitStr[i]);
29
+ }
30
+ }
31
+ return capitalizeFirst(splitStr.join(' '));
32
+ };
33
+
19
34
  const count = (str, search) => {
20
35
  if (!str || typeof str !== 'string' || !search || typeof search !== 'string') return 0;
21
36
  return (str.match(new RegExp(search, 'g')) || []).length;
@@ -27,10 +42,19 @@ const shuffle = (str) => {
27
42
  };
28
43
 
29
44
  const createRandom = (length = 12) => {
30
- if (typeof length !== 'number') return null;
31
- return Math.random().toString(36).substr(2, length).split('')
32
- .map(c => (Math.random() < 0.5 ? c.toUpperCase() : c))
33
- .join('');
45
+ if (typeof length !== 'number') {
46
+ return null;
47
+ }
48
+ let result = '';
49
+ let newChar;
50
+ const AVAIL_CHARACTERS = 'abcdefghijklmnopqrstuvwxyz0123456789';
51
+ const AVAIL_CHARACTERS_LENGTH = AVAIL_CHARACTERS.length;
52
+ for (let i = 0; i < length; i += 1) {
53
+ newChar = AVAIL_CHARACTERS.charAt(Math.floor(Math.random() * AVAIL_CHARACTERS_LENGTH));
54
+ newChar = Math.random() < 0.5 ? newChar.toUpperCase() : newChar;
55
+ result += newChar;
56
+ }
57
+ return result;
34
58
  };
35
59
 
36
60
  const hideRandom = (str, hideLength = 1, hideStr = '*') => {
@@ -58,8 +82,8 @@ const truncate = (str, length = 0, ellipsis = '') => {
58
82
  return convStr;
59
83
  };
60
84
 
61
- const encrypt = (str, secret, algorithm = 'aes-256-cbc') => {
62
- const iv = crypto.randomBytes(16);
85
+ const encrypt = (str, secret, algorithm = 'aes-256-cbc', ivSize = 16) => {
86
+ const iv = crypto.randomBytes(ivSize);
63
87
  const cipher = crypto.createCipheriv(algorithm, secret, iv);
64
88
  let enc = cipher.update(str);
65
89
  enc = Buffer.concat([enc, cipher.final()]);
@@ -74,10 +98,39 @@ const decrypt = (str, secret, algorithm = 'aes-256-cbc') => {
74
98
  return decrypted.toString();
75
99
  };
76
100
 
101
+ const md5 = (str) => {
102
+ if (!str || typeof str !== 'string' || str.length < 1) {
103
+ throw new Error('string arguments required');
104
+ }
105
+ return crypto.createHash('md5').update(str).digest('hex');
106
+ };
107
+
108
+ const sha1 = (str) => {
109
+ if (!str || typeof str !== 'string' || str.length < 1) {
110
+ throw new Error('string arguments required');
111
+ }
112
+ return crypto.createHash('sha1').update(str).digest('hex');
113
+ };
114
+
115
+ const sha256 = (str) => {
116
+ if (!str || typeof str !== 'string' || str.length < 1) {
117
+ throw new Error('string arguments required');
118
+ }
119
+ return crypto.createHash('sha256').update(str).digest('hex');
120
+ };
121
+
122
+ const unique = (str) => {
123
+ if (!str || typeof str !== 'string' || str.length < 1) {
124
+ throw new Error('string arguments required');
125
+ }
126
+ return String.prototype.concat(...new Set(str));
127
+ };
128
+
77
129
  module.exports = {
78
130
  removeSpecialChar,
79
131
  removeNewLine,
80
132
  capitalizeFirst,
133
+ capitalizeEachWords,
81
134
  count,
82
135
  shuffle,
83
136
  createRandom,
@@ -85,4 +138,8 @@ module.exports = {
85
138
  truncate,
86
139
  encrypt,
87
140
  decrypt,
141
+ md5,
142
+ sha1,
143
+ sha256,
144
+ unique,
88
145
  };
@@ -32,4 +32,11 @@ describe('Array', () => {
32
32
  assert.deepStrictEqual(_.setWithNumber(1, 1), [1]);
33
33
  done();
34
34
  });
35
+
36
+ it('average', (done) => {
37
+ assert.deepStrictEqual(_.average([1, 3, 5, 7, 9]), 5);
38
+ assert.deepStrictEqual(_.average([1, 5, 15, 50]), 17.75);
39
+ assert.deepStrictEqual(_.average([5, -5]), 0);
40
+ done();
41
+ });
35
42
  });
@@ -10,6 +10,13 @@ describe('Format', () => {
10
10
  done();
11
11
  });
12
12
 
13
+ it('fileName', (done) => {
14
+ assert.strictEqual(_.fileName('C:\\Users\\test\\Desktop\\text.txt'), 'text');
15
+ assert.strictEqual(_.fileName('/home/user/Desktop/example.txt'), 'example');
16
+ assert.strictEqual(_.fileName('C:\\example.txt', true), 'example.txt');
17
+ done();
18
+ });
19
+
13
20
  it('fileSize', (done) => {
14
21
  assert.strictEqual(_.fileExt('C:\\Users\\test\\Desktop\\text.txt'), 'txt');
15
22
  assert.strictEqual(_.fileExt('hello.html'), 'html');
@@ -40,4 +47,10 @@ describe('Format', () => {
40
47
  assert.strictEqual(_.secToTime(360000), '100:00:00');
41
48
  done();
42
49
  });
50
+
51
+ it('license', (done) => {
52
+ assert(_.license({ type: 'mit', author: 'example', yearStart: 2021 }));
53
+ assert(_.license({ author: 'example', yearStart: 2021 }));
54
+ done();
55
+ });
43
56
  });
@@ -7,6 +7,7 @@ describe('String', () => {
7
7
  assert.strictEqual(_.removeSpecialChar('Hello, World!'), 'HelloWorld');
8
8
  assert.strictEqual(_.removeSpecialChar('12 34-56,78=90'), '1234567890');
9
9
  assert.strictEqual(_.removeSpecialChar('ABC가나다ㄱㄴㄷㅏㅑㅓ天地人'), 'ABC가나다ㄱㄴㄷㅏㅑㅓ天地人');
10
+ assert.strictEqual(_.removeSpecialChar('Hello World', true), 'Hello World');
10
11
  done();
11
12
  });
12
13
 
@@ -28,6 +29,13 @@ st`), 'test');
28
29
  done();
29
30
  });
30
31
 
32
+ it('capitalizeEachWords', (done) => {
33
+ assert.strictEqual(_.capitalizeEachWords('hello, world!'), 'Hello, World!');
34
+ assert.strictEqual(_.capitalizeEachWords('test'), 'Test');
35
+ assert.strictEqual(_.capitalizeEachWords('this is the test sentence.', true), 'This is the Test Sentence.');
36
+ done();
37
+ });
38
+
31
39
  it('count', (done) => {
32
40
  assert.strictEqual(_.count('hello', 'l'), 2);
33
41
  assert.strictEqual(_.count('abcdABCD', 'a'), 1);
@@ -64,7 +72,7 @@ st`), 'test');
64
72
 
65
73
  it('encrypt', (done) => {
66
74
  assert(_.encrypt('test', '12345678901234567890123456789012'));
67
- assert(_.encrypt('test', '12345678901234567890123456789012', 'aes-256-gcm'));
75
+ assert(_.encrypt('test', '12345678901234567890123456789012', 'aes-256-gcm', 16));
68
76
  done();
69
77
  });
70
78
 
@@ -72,4 +80,28 @@ st`), 'test');
72
80
  assert.strictEqual(_.decrypt('61ba43b65fc3fc2bdbd0d1ad8576344d:1831d7c37d12b3bf7ee73195d31af91b', '12345678901234567890123456789012'), 'test');
73
81
  done();
74
82
  });
83
+
84
+ it('md5', (done) => {
85
+ assert.strictEqual(_.md5('test'), '098f6bcd4621d373cade4e832627b4f6');
86
+ assert.strictEqual(_.md5('qsu-md5'), '94af002364e42b514badb41b870ceb04');
87
+ done();
88
+ });
89
+
90
+ it('sha1', (done) => {
91
+ assert.strictEqual(_.sha1('test'), 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3');
92
+ assert.strictEqual(_.sha1('qsu-md5'), 'e5c5dc3b2be3542475671d460f906c3b176bb5bf');
93
+ done();
94
+ });
95
+
96
+ it('sha256', (done) => {
97
+ assert.strictEqual(_.sha256('test'), '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08');
98
+ assert.strictEqual(_.sha256('qsu-md5'), '8c4cfec3ec79dc572958ea7f0e3cfd24b90d174969df9a4773b37b68498871ed');
99
+ done();
100
+ });
101
+
102
+ it('unique', (done) => {
103
+ assert.strictEqual(_.unique('ababcdcd'), 'abcd');
104
+ assert.strictEqual(_.unique('abc--11111'), 'abc-1');
105
+ done();
106
+ });
75
107
  });
@@ -35,6 +35,8 @@ describe('Verify', () => {
35
35
  assert.strictEqual(_.contains('12345', '10'), false);
36
36
  assert.strictEqual(_.contains('ABC', ['A', 'B', 'C']), true);
37
37
  assert.strictEqual(_.contains('ABC', ['D', 'E', 'F']), false);
38
+ assert.strictEqual(_.contains('ABC', ['AB', 'C'], true), false);
39
+ assert.strictEqual(_.contains('AB', ['AB', 'C', 'D'], true), true);
38
40
  done();
39
41
  });
40
42
 
package/verify.js CHANGED
@@ -1,8 +1,6 @@
1
1
  const empty = (data) => {
2
2
  if (!data) return true;
3
3
  switch (typeof data) {
4
- default:
5
- return false;
6
4
  case 'string':
7
5
  return data.length < 1;
8
6
  case 'object':
@@ -10,6 +8,8 @@ const empty = (data) => {
10
8
  return data.length < 1;
11
9
  }
12
10
  return Object.keys(data).length < 1;
11
+ default:
12
+ return false;
13
13
  }
14
14
  };
15
15
 
@@ -25,12 +25,18 @@ const isUrl = (url, withProtocol = false, strict = false) => {
25
25
  return true;
26
26
  };
27
27
 
28
- const contains = (str, search) => {
28
+ const contains = (str, search, exact) => {
29
29
  if (!str || !search || (typeof str !== 'string' && typeof str !== 'object')
30
30
  || (typeof str === 'object' && !Array.isArray(str))) return false;
31
31
  if (typeof search === 'string') return str.indexOf(search) !== -1;
32
32
  for (let i = 0, iLen = search.length; i < iLen; i += 1) {
33
- if (str.indexOf(search[i]) !== -1) return true;
33
+ if (exact) {
34
+ if (str === search[i]) {
35
+ return true;
36
+ }
37
+ } else if (str.indexOf(search[i]) !== -1) {
38
+ return true;
39
+ }
34
40
  }
35
41
  return false;
36
42
  };
@@ -51,9 +57,6 @@ const between = (number, range, inclusive = false) => {
51
57
  const length = (data) => {
52
58
  if (!data || typeof data === 'undefined') return 0;
53
59
  switch (typeof data) {
54
- default:
55
- case 'string':
56
- return data.length;
57
60
  case 'object':
58
61
  return Array.isArray(data) ? data.length : Object.keys(data).length;
59
62
  case 'number':
@@ -63,12 +66,15 @@ const length = (data) => {
63
66
  return data ? 4 : 5;
64
67
  case 'function':
65
68
  return length(data());
69
+ case 'string':
70
+ default:
71
+ return data.length;
66
72
  }
67
73
  };
68
74
 
69
75
  const isBotAgent = (userAgent) => {
70
76
  if (!userAgent || typeof userAgent !== 'string' || userAgent.length < 1) return false;
71
- return new RegExp('(bot|naverbot|google|Googlebot|Googlebot-Mobile|Googlebot-Image|Google favicon|Mediapartners-Google|bingbot|slurp|java|wget|curl|Commons-HttpClient|Python-urllib|libwww|httpunit|nutch|phpcrawl|msnbot|jyxobot|FAST-WebCrawler|FAST Enterprise Crawler|biglotron|teoma|convera|seekbot|gigablast|exabot|ngbot|ia_archiver|GingerCrawler|webmon |httrack|webcrawler|grub.org|UsineNouvelleCrawler|antibot|netresearchserver|speedy|fluffy|bibnum.bnf|findlink|msrbot|panscient|yacybot|AISearchBot|IOI|ips-agent|tagoobot|MJ12bot|dotbot|woriobot|yanga|buzzbot|mlbot|yandexbot|purebot|Linguee Bot|Voyager|CyberPatrol|voilabot|baiduspider|citeseerxbot|spbot|twengabot|postrank|turnitinbot|scribdbot|page2rss|sitebot|linkdex|Adidxbot|blekkobot|ezooms|dotbot|Mail.RU_Bot|discobot|heritrix|findthatfile|europarchive.org|NerdByNature.Bot|sistrix crawler|ahrefsbot|Aboundex|domaincrawler|wbsearchbot|summify|ccbot|edisterbot|seznambot|ec2linkfinder|gslfbot|aihitbot|intelium_bot|facebookexternalhit|yeti|RetrevoPageAnalyzer|lb-spider|sogou|lssbot|careerbot|wotbox|wocbot|ichiro|DuckDuckBot|lssrocketcrawler|drupact|webcompanycrawler|acoonbot|openindexspider|gnam gnam spider|web-archive-net.com.bot|backlinkcrawler|coccoc|integromedb|content crawler spider|toplistbot|seokicks-robot|it2media-domain-crawler|ip-web-crawler.com|siteexplorer.info|elisabot|proximic|changedetection|blexbot|arabot|WeSEE:Search|niki-bot|CrystalSemanticsBot|rogerbot|360Spider|psbot|InterfaxScanBot|Lipperhey SEO Service|CC Metadata Scaper|g00g1e.net|GrapeshotCrawler|urlappendbot|brainobot|fr-crawler|binlar|SimpleCrawler|Livelapbot|Twitterbot|cXensebot|smtbot|bnf.fr_bot|A6-Indexer|ADmantX|Facebot|Twitterbot|OrangeBot|memorybot|AdvBot|MegaIndex|SemanticScholarBot|ltx71|nerdybot|xovibot|BUbiNG|Qwantify|archive.org_bot|Applebot|TweetmemeBot|crawler4j|findxbot|SemrushBot|yoozBot|lipperhey|y!j-asr|Domain Re-Animator Bot|AddThis)', 'i').test(userAgent);
77
+ return /bot|naverbot|google|Googlebot|Googlebot-Mobile|Googlebot-Image|Google favicon|Mediapartners-Google|bingbot|slurp|java|wget|curl|Commons-HttpClient|Python-urllib|libwww|httpunit|nutch|phpcrawl|msnbot|jyxobot|FAST-WebCrawler|FAST Enterprise Crawler|biglotron|teoma|convera|seekbot|gigablast|exabot|ngbot|ia_archiver|GingerCrawler|webmon |httrack|webcrawler|grub.org|UsineNouvelleCrawler|antibot|netresearchserver|speedy|fluffy|bibnum.bnf|findlink|msrbot|panscient|yacybot|AISearchBot|IOI|ips-agent|tagoobot|MJ12bot|dotbot|woriobot|yanga|buzzbot|mlbot|yandexbot|purebot|Linguee Bot|Voyager|CyberPatrol|voilabot|baiduspider|citeseerxbot|spbot|twengabot|postrank|turnitinbot|scribdbot|page2rss|sitebot|linkdex|Adidxbot|blekkobot|ezooms|dotbot|Mail.RU_Bot|discobot|heritrix|findthatfile|europarchive.org|NerdByNature.Bot|sistrix crawler|ahrefsbot|Aboundex|domaincrawler|wbsearchbot|summify|ccbot|edisterbot|seznambot|ec2linkfinder|gslfbot|aihitbot|intelium_bot|facebookexternalhit|yeti|RetrevoPageAnalyzer|lb-spider|sogou|lssbot|careerbot|wotbox|wocbot|ichiro|DuckDuckBot|lssrocketcrawler|drupact|webcompanycrawler|acoonbot|openindexspider|gnam gnam spider|web-archive-net.com.bot|backlinkcrawler|coccoc|integromedb|content crawler spider|toplistbot|seokicks-robot|it2media-domain-crawler|ip-web-crawler.com|siteexplorer.info|elisabot|proximic|changedetection|blexbot|arabot|WeSEE:Search|niki-bot|CrystalSemanticsBot|rogerbot|360Spider|psbot|InterfaxScanBot|Lipperhey SEO Service|CC Metadata Scaper|g00g1e.net|GrapeshotCrawler|urlappendbot|brainobot|fr-crawler|binlar|SimpleCrawler|Livelapbot|Twitterbot|cXensebot|smtbot|bnf.fr_bot|A6-Indexer|ADmantX|Facebot|Twitterbot|OrangeBot|memorybot|AdvBot|MegaIndex|SemanticScholarBot|ltx71|nerdybot|xovibot|BUbiNG|Qwantify|archive.org_bot|Applebot|TweetmemeBot|crawler4j|findxbot|SemrushBot|yoozBot|lipperhey|y!j-asr|Domain Re-Animator Bot|AddThis/i.test(userAgent);
72
78
  };
73
79
 
74
80
  module.exports = {