Lightweight and fast!
Aim for small footprint and fast performance. Ideal for modern NodeJS programming.
diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404.html b/404.html new file mode 100644 index 0000000..1da234c --- /dev/null +++ b/404.html @@ -0,0 +1,24 @@ + + +
+ + +_.arrShuffle
Shuffle the order of the given array and return.
array::any[]
any[]
_.arrShuffle([1, 2, 3, 4]); // Returns [4, 2, 3, 1]
_.arrWithDefault
Initialize an array with a default value of a specific length.
defaultValue::any
length::number || 0
any[]
_.arrWithDefault('abc', 4); // Returns ['abc', 'abc', 'abc', 'abc']
+_.arrWithDefault(null, 3); // Returns [null, null, null]
_.arrWithNumber
Creates and returns an Array in the order of start...end values.
start::number
end::number
number[]
_.arrWithNumber(1, 3); // Returns [1, 2, 3]
+_.arrWithNumber(0, 3); // Returns [0, 1, 2, 3]
_.arrUnique
Remove duplicate values from array and two-dimensional array data. In the case of 2d arrays, json type data duplication is not removed.
array::any[]
any[]
_.arrUnique([1, 2, 2, 3]); // Returns [1, 2, 3]
+_.arrUnique([[1], [1], [2]]); // Returns [[1], [2]]
_.average
Returns the average of all numeric values in an array.
array::number[]
number
_.average([1, 5, 15, 50]); // Returns 17.75
_.arrMove
Moves the position of a specific element in an array to the specified position. (Position starts from 0.)
array::any[]
from::number
to::number
any[]
_.arrMove([1, 2, 3, 4], 1, 0); // Returns [2, 1, 3, 4]
_.arrTo1dArray
Merges all elements of a multidimensional array into a one-dimensional array.
array::any[]
any[]
_.arrTo1dArray([1, 2, [3, 4]], 5); // Returns [1, 2, 3, 4, 5]
_.arrRepeat
Repeats the data of an Array
or Object
a specific number of times and returns it as a 1d array.
array::any[]|object
count::number
any[]
_.arrRepeat([1, 2, 3, 4], 3); // Returns [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
+_.arrRepeat({ a: 1, b: 2 }, 2); // Returns [{ a: 1, b: 2 }, { a: 1, b: 2 }]
_.arrCount
Returns the number of duplicates for each unique value in the given array. The array values can only be of type String
or Number
.
array::string[]|number[]
count::number
object
_.arrCount(['a', 'a', 'a', 'b', 'c', 'b', 'a', 'd']); // Returns { a: 4, b: 2, c: 1, d: 1 }
_.sortByObjectKey
Sort array values by a specific key value in an array containing multiple objects. It does not affect the order or value of elements within an object.
If the numerically
option is true
, when sorting an array consisting of strings, it sorts first by the numbers contained in the strings, not by their names.
array::any[]
key::string
descending::boolean
numerically::boolean
any[]
const obj = [
+ {
+ aa: 1,
+ bb: 'aaa',
+ cc: 'hi1'
+ },
+ {
+ aa: 4,
+ bb: 'ccc',
+ cc: 'hi10'
+ },
+ {
+ aa: 2,
+ bb: 'ddd',
+ cc: 'hi2'
+ },
+ {
+ aa: 3,
+ bb: 'bbb',
+ cc: 'hi11'
+ }
+];
+
+_.sortByObjectKey(obj, 'aa');
+
+/*
+[
+ {
+ aa: 1,
+ bb: 'aaa',
+ cc: 'hi1'
+ },
+ {
+ aa: 2,
+ bb: 'ddd',
+ cc: 'hi2'
+ },
+ {
+ aa: 3,
+ bb: 'bbb',
+ cc: 'hi11'
+ },
+ {
+ aa: 4,
+ bb: 'ccc',
+ cc: 'hi10'
+ }
+]
+*/
_.sortNumeric
When sorting an array consisting of strings, it sorts first by the numbers contained in the strings, not by their names. For example, given the array ['1-a', '100-a', '10-a', '2-a']
, it returns ['1-a', '2-a', '10-a', '100-a']
with the smaller numbers at the front.
array::string[]
descending::boolean
string[]
_.sortNumeric(['a1a', 'b2a', 'aa1a', '1', 'a11a', 'a3a', 'a2a', '1a']);
+// Returns ['1', '1a', 'a1a', 'a2a', 'a3a', 'a11a', 'aa1a', 'b2a']
_.arrGroupByMaxCount
Separates the data in the given array into a two-dimensional array containing only the maximum number of elements. For example, if you have an array of 6 data in 2 groups, this function will create a 2-dimensional array with 3 lengths.
array::any[]
maxLengthPerGroup::number
any[]
_.arrGroupByMaxCount(['a', 'b', 'c', 'd', 'e'], 2);
+// Returns [['a', 'b'], ['c', 'd'], ['e']]
_.encrypt
Encrypt with the algorithm of your choice (algorithm default: aes-256-cbc
, ivSize default: 16
) using a string and a secret (secret).
str::string
secret::string
algorithm::string || 'aes-256-cbc'
ivSize::number || 16
string
_.encrypt('test', 'secret-key');
_.decrypt
Decrypt with the specified algorithm (default: aes-256-cbc
) using a string and a secret (secret).
str::string
secret::string
algorithm::string || 'aes-256-cbc'
string
_.decrypt('61ba43b65fc...', 'secret-key');
_.objectId
Returns a random string hash of the ObjectId format (primarily utilized by MongoDB).
No parameters required
string
_.objectId(); // Returns '651372605b49507aea707488'
_.md5
Converts String data to md5 hash value and returns it.
str::string
string
_.md5('test'); // Returns '098f6bcd4621d373cade4e832627b4f6'
_.sha1
Converts String data to sha1 hash value and returns it.
str::string
string
_.sha1('test'); // Returns 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
_.sha256
Converts String data to sha256 hash value and returns it.
str::string
string
_.sha256('test'); // Returns '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
_.encodeBase64
Base64-encode the given string.
str::string
string
_.encodeBase64('this is test'); // Returns 'dGhpcyBpcyB0ZXN0'
_.decodeBase64
Decodes an encoded base64 string to a plain string.
encodedStr::string
string
_.decodeBase64('dGhpcyBpcyB0ZXN0'); // Returns 'this is test'
_.strToNumberHash
Returns the specified string as a hash value of type number. The return value can also be negative.
str::string
number
_.strToNumberHash('abc'); // Returns 96354\n_.strToNumberHash('Hello'); // Returns 69609650\n_.strToNumberHash('hello'); // Returns 99162322
_.dayDiff
Calculates the difference between two given dates and returns the number of days.
date1::Date
date2::Date?
number
_.daydiff(new Date('2021-01-01'), new Date('2021-01-03')); // Returns 2
_.today
Returns today's date.
separator::string = '-'
yearFirst::boolean = false
string
_.today(); // Returns YYYY-MM-DD
+_.today('/'); // Returns YYYY/MM/DD
+_.today('/', false); // Returns DD/MM/YYYY
_.isValidDate
Checks if a given date actually exists. Check only in YYYY-MM-DD
format.
date::string
boolean
_.isValidDate('2021-01-01'); // Returns true
+_.isValidDate('2021-02-30'); // Returns false
_.dateToYYYYMMDD
Returns the date data of a Date object in the format YYYY-MM-DD
.
date::Date
separator:string
string
_.dateToYYYYMMDD(new Date(2023, 11, 31)); // Returns '2023-12-31'
_.createDateListFromRange
Create an array list of all dates from startDate
to endDate
in the format YYYY-MM-DD
.
startDate::Date
endDate::Date
string[]
_.createDateListFromRange(new Date('2023-01-01T01:00:00Z'), new Date('2023-01-05T01:00:00Z'));
+
+/*
+ [
+ '2023-01-01',
+ '2023-01-02',
+ '2023-01-03',
+ '2023-01-04',
+ '2023-01-05'
+ ]
+ */
_.numberFormat
Return number format including comma symbol.
number::number
string
_.numberFormat(1234567); // Returns 1,234,567
_.fileName
Extract the file name from the path. Include the extension if withExtension is true
.
filePath::string
withExtension::boolean || false
string
_.fileName('C:Temphello.txt'); // Returns 'hello.txt'\n_.fileName('C:Temp\\file.mp3', true); // Returns 'file.mp3'
_.fileSize
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.
bytes::number
decimals::number || 2
string
_.fileSize(2000, 3); // Returns '1.953 KB'\n_.fileSize(250000000); // Returns '238.42 MB'
_.fileExt
Returns only the extensions in the file path. If unknown, returns 'Unknown'.
filePath::string
string
_.fileExt('C:Temphello.txt'); // Returns 'txt'\n_.fileExt('this-is-file.mp3'); // Returns 'mp3'
_.duration
Displays the given millisecond value in human-readable time. For example, the value of 604800000
(7 days) is displayed as 7 Days
.
milliseconds::number
options::DurationOptions | undefined
const {\n // Converts to `Days` -> `D`, `Hours` -> `H`, `Minutes` -> `M`, `Seconds` -> `S`, `Milliseconds` -> `ms`\n useShortString = false,\n // Use space (e.g. `1Days` -> `1 Days`)\n useSpace = true,\n // Do not include units with a value of 0.\n withZeroValue = false,\n // Use Separator (e.g. If separator value is `-`, result is: `1 Hour 10 Minutes` -> `1 Hour-10 Minutes`)\n separator = ' '\n}: DurationOptions = options;
string
_.duration(1234567890); // 'Returns '14 Days 6 Hours 56 Minutes 7 Seconds 890 Milliseconds'\n_.duration(604800000, {\n useSpace: false\n}); // Returns '7Days'
_.safeJSONParse
Attempts to parse without returning an error, even if the argument value is of the wrong type or in JSON
format. If parsing fails, it will be replaced with the object set in fallback
.fallback
의 기본값은 빈 오브젝트입니다.
jsonString::any
fallback::object
object
const result1 = _.safeJSONParse('{"a":1,"b":2}');\nconst result2 = _.safeJSONParse(null);\n\nconsole.log(result1); // Returns { a: 1, b: 2 }\nconsole.log(result2); // Returns {}
_.safeParseInt
Any argument value will be attempted to be parsed as a Number type without returning an error. If parsing fails, it is replaced by the number set in fallback
. The default value for fallback
is 0
. You can specify radix
(default is decimal: 10
) in the third argument.
value::any
fallback::number
radix::number
number
const result1 = _.safeParseInt('00010');\nconst result2 = _.safeParseInt('10.1234');\nconst result3 = _.safeParseInt(null, -1);\n\nconsole.log(result1); // Returns 10\nconsole.log(result2); // Returns 10\nconsole.log(result3); // Returns -1
_.numRandom
Returns a random number (Between min and max).
min::number
max::number
number
_.numRandom(1, 5); // Returns 1~5\n_.numRandom(10, 20); // Returns 10~20
_.sum
Returns after adding up all the n arguments of numbers or the values of a single array of numbers.
numbers::...number[]
number
_.sum(1, 2, 3); // Returns 6\n_.sum([1, 2, 3, 4]); // Returns 10
_.mul
Returns after multiplying all n arguments of numbers or the values of a single array of numbers.
numbers::...number[]
number
_.mul(1, 2, 3); // Returns 6\n_.mul([1, 2, 3, 4]); // Returns 24
_.sub
Returns after subtracting all n arguments of numbers or the values of a single array of numbers.
numbers::...number[]
number
_.sub(10, 1, 5); // Returns 4\n_.sub([1, 2, 3, 4]); // Returns -8
_.div
Returns after dividing all n arguments of numbers or the values of a single array of numbers.
numbers::...number[]
number
_.div(10, 5, 2); // Returns 1\n_.div([100, 2, 2, 5]); // Returns 5
_.sleep
Sleep function using Promise.
milliseconds::number
Promise:boolean
await _.sleep(1000); // 1s
+
+_.sleep(5000).then(() => {
+ // continue
+});
_.funcTimes
Repeat iteratee n (times argument value) times. After the return result of each function is stored in the array in order, the final array is returned.
times::number
iteratee::function
any[]
function sayHi(str) {
+ return \`Hi\${str || ''}\`;
+}
+
+_.funcTimes(3, sayHi); // Returns ['Hi', 'Hi', 'Hi']
+_.funcTimes(4, () => sayHi('!')); // Returns ['Hi!', 'Hi!', 'Hi!', 'Hi!']
_.debounce
When the given function is executed repeatedly, the function is called if it has not been called again within the specified timeout. This function is used when a small number of function calls are needed for repetitive input events.
For example, if you have a func
variable written as const func = debounce(() => console.log('hello'), 1000)
and you repeat the func
function 100 times with a wait interval of 100ms, the function will only run once after 1000ms because the function was executed at 100ms intervals. However, if you increase the wait interval from 100ms to 1100ms or more and repeat it 100 times, the function will run all 100 times intended.
func::function
timeout::number
No return values
<!doctype html>
+<html lang="en">
+ <head>
+ <title>test</title>
+ </head>
+ <body>
+ <input type="text" onkeyup="handleKeyUp()" />
+ </body>
+</html>
+<script>
+ import _ from 'qsu';
+
+ const keyUpDebounce = _.debounce(() => {
+ console.log('handleKeyUp called.');
+ }, 100);
+
+ function handleKeyUp() {
+ keyUpDebounce();
+ }
+</script>
_.objToQueryString
Converts the given object data to a URL query string.
obj::object
string
_.objToQueryString({
+ hello: 'world',
+ test: 1234,
+ arr: [1, 2, 3]
+}); // Returns 'hello=world&test=1234&arr=%5B1%2C2%2C3%5D'
_.objToPrettyStr
Recursively output all the steps of the JSON object (JSON.stringify
) and then output the JSON object with newlines and tab characters to make it easier to read in a console
function, for example.
obj::object
string
_.objToPrettyStr({ a: 1, b: { c: 1, d: 2 } }); // Returns '{\\n\\t"a": 1,\\n\\t"b": {\\n\\t\\t"c": 1,\\n\\t\\t"d": 2\\n\\t}\\n}'
_.objFindItemRecursiveByKey
Returns the object if the key of a specific piece of data in the object's dataset corresponds to a specific value. This function returns only one result, so it is used to search for unique IDs, including all of their children.
obj::object
searchKey::string
searchValue::any
childKey::string
object|null
_.objFindItemRecursiveByKey(
+ {
+ id: 123,
+ name: 'parent',
+ child: [
+ {
+ id: 456,
+ name: 'childItemA'
+ },
+ {
+ id: 789,
+ name: 'childItemB'
+ }
+ ]
+ }, // obj
+ 'id', // searchKey
+ 456, // searchValue
+ 'child' // childKey
+); // Returns '{ id: 456, name: 'childItemA' }'
_.objToArray
Converts the given object to array format. The resulting array is a two-dimensional array with one key value stored as follows: [key, value]
. If the recursive
option is true
, it will convert to a two-dimensional array again when the value is of type object
.
obj::object
recursive::boolean
any[]
_.objToArray({
+ a: 1.234,
+ b: 'str',
+ c: [1, 2, 3],
+ d: { a: 1 }
+}); // Returns [['a', 1.234], ['b', 'str'], ['c', [1, 2, 3]], ['d', { a: 1 }]]
_.objTo1d
Merges objects from the given object to the top level of the child items and displays the key names in steps, using a delimiter (.
by default) instead of the existing keys. For example, if an object a
has keys b
, c
, and d
, the a
key is not displayed, and the keys and values a.b
, a.c
, and a.d
are displayed in the parent step.
obj::object
separator::string
object
_.objToArray({
+ a: 1,
+ b: {
+ aa: 1,
+ bb: 2
+ },
+ c: 3
+});
+
+/*
+Returns:
+{
+ a: 1,
+ 'b.aa': 1,
+ 'b.bb': 2,
+ c: 3
+}
+ */
_.objDeleteKeyByValue
Deletes keys equal to the given value from the object data. If the recursive
option is true
, also deletes all keys corresponding to the same value in the child items.
obj::object
searchValue::string|number|null|undefined
recursive::boolean
object|null
const result = _.objDeleteKeyByValue(
+ {
+ a: 1,
+ b: 2,
+ c: {
+ aa: 2,
+ bb: {
+ aaa: 1,
+ bbb: 2
+ }
+ },
+ d: {
+ aa: 2
+ }
+ },
+ 2,
+ true
+);
+
+console.log(result); // Returns { a: 1, c: { bb: { aaa: 1 } }, d: {} }
_.objUpdate
Changes the value matching a specific key name in the given object. If the recursive
option is true
, it will also search in child object items. This changes the value of the same key found in both the parent and child items. If the upsert
option is true
, add it as a new attribute to the top-level item when the key is not found.
obj::object
searchKey::string
value::any
recursive::boolean
upsert::boolean
object|null
const result = _.objUpdate(
+ {
+ a: 1,
+ b: {
+ a: 1,
+ b: 2,
+ c: 3
+ },
+ c: 3
+ },
+ 'c',
+ 5,
+ true,
+ false
+);
+
+console.log(result); // Returns { a: 1, b: { a: 1, b: 2, c: 5 }, c: 5 }
_.trim
Removes all whitespace before and after a string. Unlike JavaScript's trim
function, it converts two or more spaces between sentences into a single space.
str::string
string
_.trim(' Hello Wor ld '); // Returns 'Hello Wor ld'\n_.trim('H e l l o World'); // Returns 'H e l l o World'
_.removeSpecialChar
Returns after removing all special characters, including spaces. If you want to allow any special characters as exceptions, list them in the second argument value without delimiters. For example, if you want to allow spaces and the symbols &
and *
, the second argument value would be ' &*'.
str::string
exceptionCharacters::string?
string
_.removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'\n_.removeSpecialChar('Hello-qsu, World!', ' -'); // Returns 'Hello-qsu World'
_.removeNewLine
Removes \\n
, \\r
characters or replaces them with specified characters.
str::string
replaceTo::string || ''
string
_.removeNewLine('ab\\ncd'); // Returns 'abcd'\n_.removeNewLine('ab\\r\\ncd', '-'); // Returns 'ab-cd'
_.replaceBetween
Replaces text within a range starting and ending with a specific character in a given string with another string. For example, given the string abc<DEF>ghi
, to change <DEF>
to def
, use replaceBetween('abc<DEF>ghi', '<', '>', 'def')
. The result would be abcdefghi
.
Deletes strings in the range if replaceWith
is not specified.
str::string
startChar::string
endChar::string
replaceWith::string || ''
string
_.replaceBetween('ab[c]d[e]f', '[', ']'); // Returns 'abdf'\n_.replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
_.capitalizeFirst
Converts the first letter of the entire string to uppercase and returns.
str::string
string
_.capitalizeFirst('abcd'); // Returns 'Abcd'
_.capitalizeEverySentence
Capitalize the first letter of every sentence. Typically, the .
characters to separate sentences, but this can be customized via the value of the splitChar
argument.
str::string
splitChar::string
string
_.capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'\n_.capitalizeEverySentence('hello!world', '!'); // Returns 'Hello!World'
_.capitalizeEachWords
Converts every word with spaces to uppercase. If the naturally argument is true, only some special cases (such as prepositions) are kept lowercase.
str::string
natural::boolean || false
string
_.capitalizeEachWords('abcd'); // Returns 'Abcd'
_.strCount
Returns the number of times the second String argument is contained in the first String argument.
str::string
search::string
number
_.strCount('abcabc', 'a'); // Returns 2
_.strShuffle
Randomly shuffles the received string and returns it.
str::string
string
_.strShuffle('abcdefg'); // Returns 'bgafced'
_.strRandom
Returns a random String containing numbers or uppercase and lowercase letters of the given length. The default return length is 12.
length::number
additionalCharacters::string?
string
_.strRandom(5); // Returns 'CHy2M'
_.strBlindRandom
Replace strings at random locations with a specified number of characters (default 1) with characters (default *).
str::string
blindLength::number
blindStr::string || '*'
string
_.strBlindRandom('hello', 2, '#'); // Returns '#el#o'
_.truncate
Truncates a long string to a specified length, optionally appending an ellipsis after the string.
str::string
length::number
ellipsis::string || ''
string
_.truncate('hello', 3); // Returns 'hel'\n_.truncate('hello', 2, '...'); // Returns 'he...'
_.truncateExpect
The string ignores truncation until the ending character (endStringChar
). If the expected length is reached, return the truncated string until after the ending character.
str::string
expectLength::number
endStringChar::string || '.'
string
_.truncateExpect('hello. this is test string.', 10, '.'); // Returns 'hello. this is test string.'\n_.truncateExpect('hello-this-is-test-string-bye', 14, '-'); // Returns 'hello-this-is-'
_.split
Splits a string based on the specified character and returns it as an Array. Unlike the existing split, it splits the values provided as multiple parameters (array or multiple arguments) at once.
str::string
splitter::string||string[]||...string
string[]
_.split('hello% js world', '% '); // Returns ['hello', 'js world']\n_.split('hello,js,world', ','); // Returns ['hello', 'js', 'world']\n_.split('hello%js,world', ',', '%'); // Returns ['hello', 'js', 'world']\n_.split('hello%js,world', [',', '%']); // Returns ['hello', 'js', 'world']
_.strUnique
Remove duplicate characters from a given string and output only one.
str::string
string
_.strUnique('aaabbbcc'); // Returns 'abc'
_.strToAscii
Converts the given string to ascii code and returns it as an array.
str::string
number[]
_.strToAscii('12345'); // Returns [49, 50, 51, 52, 53]
_.urlJoin
Merges the given string argument with the first argument (the beginning of the URL), joining it so that the slash (/
) symbol is correctly included.
args::any[]
string
_.urlJoin('https://example.com', 'hello', 'world'); // Returns 'https://example.com/hello/world'
_.isObject
Check whether the given data is of type Object
. Returns false
for other data types including Array
.
data::any
boolean
_.isObject([1, 2, 3]); // Returns false
+_.isObject({ a: 1, b: 2 }); // Returns true
_.isEqual
It compares the first argument value as the left operand and the argument values given thereafter as the right operand, and returns true
if the values are all the same.
isEqual
returns true
even if the data types do not match, but isEqualStrict
returns true
only when the data types of all argument values match.
leftOperand::any
rightOperand::any||any[]||...any
boolean
const val1 = 'Left';
+const val2 = 1;
+
+_.isEqual('Left', 'Left', val1); // Returns true
+_.isEqual(1, [1, '1', 1, val2]); // Returns true
+_.isEqual(val1, ['Right', 'Left', 1]); // Returns false
+_.isEqual(1, 1, 1, 1); // Returns true
_.isEqualStrict
It compares the first argument value as the left operand and the argument values given thereafter as the right operand, and returns true
if the values are all the same.
isEqual
returns true
even if the data types do not match, but isEqualStrict
returns true
only when the data types of all argument values match.
leftOperand::any
rightOperand::any||any[]||...any
boolean
const val1 = 'Left';
+const val2 = 1;
+
+_.isEqualStrict('Left', 'Left', val1); // Returns true
+_.isEqualStrict(1, [1, '1', 1, val2]); // Returns false
+_.isEqualStrict(1, 1, '1', 1); // Returns false
_.isEmpty
Returns true if the passed data is empty or has a length of 0.
data::any?
boolean
_.isEmpty([]); // Returns true
+_.isEmpty(''); // Returns true
+_.isEmpty('abc'); // Returns false
_.isUrl
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
.
url::string
withProtocol::boolean || false
strict::boolean || false
boolean
_.isUrl('google.com'); // Returns false
+_.isUrl('google.com', true); // Returns true
+_.isUrl('https://google.com'); // Returns true
_.contains
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.
str::any[]|string
search::any[]|string
exact::boolean || false
boolean
_.contains('abc', 'a'); // Returns true
+_.contains('abc', 'd'); // Returns false
+_.contains('abc', ['a', 'd']); // Returns true
_.is2dArray
Returns true
if the given array is a two-dimensional array.
array::any[]
boolean
_.is2dArray([1]); // Returns false
+_.is2dArray([[1], [2]]); // Returns true
_.between
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.
range::[number, number]
number::number
inclusive::boolean || false
boolean
_.between([10, 20], 10); // Returns false
+_.between([10, 20], 10, true); // Returns true
_.len
Returns the length of any type of data. If the argument value is null
or undefined
, 0
is returned.
data::any
boolean
_.len('12345'); // Returns 5
+_.len([1, 2, 3]); // Returns 3
_.isEmail
Checks if the given argument value is a valid email.
email::string
boolean
_.isEmail('abc@def.com'); // Returns true
_.isTrueMinimumNumberOfTimes
Returns true
if the values given in the conditions
array are true at least minimumCount
times.
conditions::boolean[]
minimumCount::number
boolean
const left = 1;
+const right = 1 + 2;
+
+_.isTrueMinimumNumberOfTimes([true, true, false], 2); // Returns true
+_.isTrueMinimumNumberOfTimes([true, true, false], 3); // Returns false
+_.isTrueMinimumNumberOfTimes([true, true, left === right], 3); // Returns false
isObject
: use more accurate detect logicsafeJSONParse
: Add safeJSONParse
methodsafeParseInt
: Add safeParseInt
methodmsToTime
and secToTime
methods, which are unstable and have been replaced with the duration
method to provide a more stable utility.duration
: Add duration
methodobjectTo1d
: Add objectTo1d
methodtrim
: handle error when value is null
trim
, Now there is no second argument, and the default behavior is to remove leading and trailing spaces, and change spaces in more than two letters to spaces in the sentencegetPlatform
method has been deletednumberFormat
: allow string type parameterisTrueMinimumNumberOfTimes
: Add isTrueMinimumNumberOfTimes
methodobjDeleteKeyByValue
: Add objDeleteKeyByValue
methodobjUpdate
: Add objUpdate
methodarrGroupByMaxCount
: Add arrGroupByMaxCount
methodobjFindItemRecursiveByKey
: Add objFindItemRecursiveByKey
methodurlJoin
: Add urlJoin
methodobjToArray
: Add objToArray
methodstrToNumberHash
: Add strToNumberHash
methodobjToQueryString
: Add objToQueryString
methodobjToPrettyStr
: Add objToPrettyStr
methodencrypt
, decrypt
: Add toBase64 params for result string encodingcreateDateListFromRange
: Use regex instead of string checkgetPlatform
: Android is not linux os (This method has now been removed in version 1.3.6)objectId
: Add objectId
methodsortByObjectKey
: Add sortByObjectKey
methodsortNumeric
: Add sortNumeric
methodtruncateExpect
: do not add a closing character to the last character for sentences without a closing characterreplaceBetween
: Add replaceBetween
methodcapitalizeEverySentence
: Add capitalizeEverySentence
methodarrUnique
: Use fast algorithm for 2d array uniquedebounce
: Add debounce
methodBREAKING CHANGES: The isBotAgent
, license
methods were separated from qsu
to the qsu-web
package. These methods are no longer available after version 1.2.0.
qsu-web
package: https://github.com/jooy2/qsu-webstrToAscii
: Add strToAscii
methodtruncateExpect
: Add truncateExpect
methodremoveSpecialChar
: Using exceptionCharacters
instead of withoutSpace
isValidDate
: Only the yyyy-mm-dd
format can be verifieddateToYYYYMMDD
: Add dateToYYYYMMDD
methodcreateDateListFromRange
: Add createDateListFromRange
methodarrCount
: Add arrCount
methodisEmail
: Add isEmail
methodsub
: Add sub
methoddiv
: Add div
methodarrTo1dArray
: Add arrTo1dArray
methodisObject
: Add isObject
methodarrRepeat
: Add arrRepeat
methodisValidDate
: Rename isRealDate
to isValidDate
funcTimes
: Add funcTimes
methodgetPlatform
: Add getPlatform
method (This method has now been removed in version 1.3.6)sum
, mul
, split
: Fix type errorarrUnique
, capitalizeEachWords
, strBlindRandom
: Fix correct use static methodtrim
: Add new trim methodfileSize
: When byte is null, returns 0 bytesstrCount
: Use indexOf instead of regular expression to use better performancestrNumberOf
: Rename method name to strCountisBotAgent
: Remove duplicate stringstr
: Handling of null str valuestruncate
: Return empty string when str is nullfileName
: Resolves windows path regardless of system environmentCHANGELOG.md
to .npmignore
isBotAgent
: Add chrome-lighthouse
in bot listssplit
: Fix incorrect return typeisEqual
: Add new isEqual methodisEqualStrict
: Add new isEqualStrict methodcontains
: When the length of the str parameter value of string type is 0, no error is thrown and false is returnedBREAKING CHANGES: convertDate
is no longer supported due to the removal of moment
as a dependent module.
The today
method has changed its usage. We no longer support custom date formats.
split
: Add new split methodtoday
: Remove dependent modules, change parameters to use pure codeconvertDate
: Remove methodencrypt
, decrypt
: Add basic validation check (more fix)encrypt
, decrypt
: Add basic validation checkencrypt
decrypt
: Add basic validation checkstrBlindRandom
: Override the deprecated substr method=0)c=r.activeElement;else{var f=i.tabbableGroups[0],p=f&&f.firstTabbableNode;c=p||h("fallbackFocus")}if(!c)throw new Error("Your focus-trap needs to have at least one focusable element");return c},v=function(){if(i.containerGroups=i.containers.map(function(c){var f=br(c,a.tabbableOptions),p=wr(c,a.tabbableOptions),C=f.length>0?f[0]:void 0,I=f.length>0?f[f.length-1]:void 0,M=p.find(function(m){return le(m)}),P=p.slice().reverse().find(function(m){return le(m)}),z=!!f.find(function(m){return se(m)>0});return{container:c,tabbableNodes:f,focusableNodes:p,posTabIndexesFound:z,firstTabbableNode:C,lastTabbableNode:I,firstDomTabbableNode:M,lastDomTabbableNode:P,nextTabbableNode:function(x){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,K=f.indexOf(x);return K<0?$?p.slice(p.indexOf(x)+1).find(function(Q){return le(Q)}):p.slice(0,p.indexOf(x)).reverse().find(function(Q){return le(Q)}):f[K+($?1:-1)]}}}),i.tabbableGroups=i.containerGroups.filter(function(c){return c.tabbableNodes.length>0}),i.tabbableGroups.length<=0&&!h("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(i.containerGroups.find(function(c){return c.posTabIndexesFound})&&i.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},y=function w(c){var f=c.activeElement;if(f)return f.shadowRoot&&f.shadowRoot.activeElement!==null?w(f.shadowRoot):f},b=function w(c){if(c!==!1&&c!==y(document)){if(!c||!c.focus){w(d());return}c.focus({preventScroll:!!a.preventScroll}),i.mostRecentlyFocusedNode=c,Ar(c)&&c.select()}},E=function(c){var f=h("setReturnFocus",c);return f||(f===!1?!1:c)},g=function(c){var f=c.target,p=c.event,C=c.isBackward,I=C===void 0?!1:C;f=f||Ae(p),v();var M=null;if(i.tabbableGroups.length>0){var P=l(f,p),z=P>=0?i.containerGroups[P]:void 0;if(P<0)I?M=i.tabbableGroups[i.tabbableGroups.length-1].lastTabbableNode:M=i.tabbableGroups[0].firstTabbableNode;else if(I){var m=ft(i.tabbableGroups,function(B){var U=B.firstTabbableNode;return f===U});if(m<0&&(z.container===f||_e(f,a.tabbableOptions)&&!le(f,a.tabbableOptions)&&!z.nextTabbableNode(f,!1))&&(m=P),m>=0){var x=m===0?i.tabbableGroups.length-1:m-1,$=i.tabbableGroups[x];M=se(f)>=0?$.lastTabbableNode:$.lastDomTabbableNode}else ge(p)||(M=z.nextTabbableNode(f,!1))}else{var K=ft(i.tabbableGroups,function(B){var U=B.lastTabbableNode;return f===U});if(K<0&&(z.container===f||_e(f,a.tabbableOptions)&&!le(f,a.tabbableOptions)&&!z.nextTabbableNode(f))&&(K=P),K>=0){var Q=K===i.tabbableGroups.length-1?0:K+1,q=i.tabbableGroups[Q];M=se(f)>=0?q.firstTabbableNode:q.firstDomTabbableNode}else ge(p)||(M=z.nextTabbableNode(f))}}else M=h("fallbackFocus");return M},S=function(c){var f=Ae(c);if(!(l(f,c)>=0)){if(ye(a.clickOutsideDeactivates,c)){s.deactivate({returnFocus:a.returnFocusOnDeactivate});return}ye(a.allowOutsideClick,c)||c.preventDefault()}},T=function(c){var f=Ae(c),p=l(f,c)>=0;if(p||f instanceof Document)p&&(i.mostRecentlyFocusedNode=f);else{c.stopImmediatePropagation();var C,I=!0;if(i.mostRecentlyFocusedNode)if(se(i.mostRecentlyFocusedNode)>0){var M=l(i.mostRecentlyFocusedNode),P=i.containerGroups[M].tabbableNodes;if(P.length>0){var z=P.findIndex(function(m){return m===i.mostRecentlyFocusedNode});z>=0&&(a.isKeyForward(i.recentNavEvent)?z+1
j)for(;E<=B;)Le(u[E],b,S,!0),E++;else{const q=E,X=E,ee=new Map;for(E=X;E<=j;E++){const be=d[E]=R?Xe(d[E]):Ae(d[E]);be.key!=null&&ee.set(be.key,E)}let Q,ae=0;const Te=j-X+1;let ht=!1,Xr=0;const St=new Array(Te);for(E=0;E {const{el:S,type:O,transition:x,children:R,shapeFlag:E}=u;if(E&6){nt(u.component.subTree,d,g,v);return}if(E&128){u.suspense.move(d,g,v);return}if(E&64){O.move(u,d,g,dt);return}if(O===_e){r(S,d,g);for(let B=0;B Qsu requires Qsu is ESM-only. You must use After configuring the node environment, you can simply run the following command. Qsu has utilities organized into separate packages. Currently, there is a package called The General installation and use is almost identical to the This method is only available in the Analyze the user agent value to determine if it's a bot for a search engine. Returns boolean Returns text in a specific license format based on the author information of the given argument. The argument uses the Object type. string Quick and Simple Utility for JavaScript QSU is a lightweight and simple module with a variety of built-in utility functions that you can utilize in your NodeJS projects.How to Use
Using named import (Multiple utilities in a single require) - Recommend
import { today, strCount } from 'qsu';
+
+function main() {
+ console.log(today()); // '20xx-xx-xx'
+ console.log(strCount('123412341234', '1')); // 3
+}
Using whole class (multiple utilities simultaneously with one object)
import _ from 'qsu';
+
+function main() {
+ console.log(_.today()); // '20xx-xx-xx'
+}
Installation
Node.js 18.x
or higher, and the repository is serviced through NPM.import
instead of require
to load the module. There are workarounds available for CommonJS, but we recommend using ESM based on recent JavaScript trends.# via npm
+$ npm install qsu
+
+# via yarn
+$ yarn add qsu
+
+# via pnpm
+$ pnpm install qsu
qsu-web
Installation qsu-web
.qsu-web
package contains a collection of utility functions that are commonly used on web pages.qsu
package.# via npm
+$ npm install qsu-web
+
+# via yarn
+$ yarn add qsu-web
+
+# via pnpm
+$ pnpm install qsu-web
import { isBotAgent } from 'qsu-web';
+
+function main() {
+ console.log(
+ isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html')
+ ); // true
+}
Methods: Web
qsu-web
package._.isBotAgent
true
if it's a bot.Parameters
userAgent::string
Returns
Examples
_.isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); // Returns true
_.license
Parameters
options::LicenseOption{ author: string, email: string?, yearStart: string|number, yearEnd: string?, htmlBr: boolean?, type: 'mit' | 'apache20' }
Returns
Examples
_.license({
+ holder: 'example',
+ email: 'example@example.com',
+ yearStart: 2020,
+ yearEnd: 2021,
+ htmlBr: true
+});
QSU