Lightweight and fast!
Aim for small footprint and fast performance. Ideal for modern 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..09080b4 --- /dev/null +++ b/404.html @@ -0,0 +1,24 @@ + + +
+ + +Shuffle the order of the given array and return.
array::any[]
any[]
_.arrShuffle([1, 2, 3, 4]); // Returns [4, 2, 3, 1]
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]
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]
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]]
Returns the average of all numeric values in an array.
array::number[]
number
_.average([1, 5, 15, 50]); // Returns 17.75
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]
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]
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 }]
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 }
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'
+ }
+]
+*/
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']
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']]
Shuffle the order of the given array and return.
array::any[]
any[]
_.arrShuffle([1, 2, 3, 4]); // Returns [4, 2, 3, 1]
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]
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]
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]]
Returns the average of all numeric values in an array.
array::number[]
number
_.average([1, 5, 15, 50]); // Returns 17.75
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]
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]
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 }]
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 }
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'
+ }
+]
+*/
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']
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 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 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');
Returns a random string hash of the ObjectId format (primarily utilized by MongoDB).
No parameters required
string
_.objectId(); // Returns '651372605b49507aea707488'
Converts String data to md5 hash value and returns it.
str::string
string
_.md5Hash('test'); // Returns '098f6bcd4621d373cade4e832627b4f6'
Converts String data to sha1 hash value and returns it.
str::string
string
_.sha1Hash('test'); // Returns 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
Converts String data to sha256 hash value and returns it.
str::string
string
_.sha256Hash('test'); // Returns '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
Base64-encode the given string.
str::string
string
_.encodeBase64('this is test'); // Returns 'dGhpcyBpcyB0ZXN0'
Decodes an encoded base64 string to a plain string.
encodedStr::string
string
_.decodeBase64('dGhpcyBpcyB0ZXN0'); // Returns 'this is test'
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
+_.strToNumberHash('Hello'); // Returns 69609650
+_.strToNumberHash('hello'); // Returns 99162322
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 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');
Returns a random string hash of the ObjectId format (primarily utilized by MongoDB).
No parameters required
string
_.objectId(); // Returns '651372605b49507aea707488'
Converts String data to md5 hash value and returns it.
str::string
string
_.md5Hash('test'); // Returns '098f6bcd4621d373cade4e832627b4f6'
Converts String data to sha1 hash value and returns it.
str::string
string
_.sha1Hash('test'); // Returns 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
Converts String data to sha256 hash value and returns it.
str::string
string
_.sha256Hash('test'); // Returns '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
Base64-encode the given string.
str::string
string
_.encodeBase64('this is test'); // Returns 'dGhpcyBpcyB0ZXN0'
Decodes an encoded base64 string to a plain string.
encodedStr::string
string
_.decodeBase64('dGhpcyBpcyB0ZXN0'); // Returns 'this is test'
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
+_.strToNumberHash('Hello'); // Returns 69609650
+_.strToNumberHash('hello'); // Returns 99162322
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
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
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
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'
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'
+ ]
+ */
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
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
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
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'
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'
+ ]
+ */
Return number format including comma symbol.
number::number
string
_.numberFormat(1234567); // Returns 1,234,567
numberFormat(1234567); // Returns 1,234,567
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'
+_.fileName('C:Temp\\file.mp3', true); // Returns 'file.mp3'
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'
+_.fileSize(250000000); // Returns '238.42 MB'
Returns only the extensions in the file path. If unknown, returns 'Unknown'.
filePath::string
string
_.fileExt('C:Temphello.txt'); // Returns 'txt'
+_.fileExt('this-is-file.mp3'); // Returns 'mp3'
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'
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
. The default value for fallback
is an empty object.
jsonString::any
fallback::object
object
const result1 = _.safeJSONParse('{"a":1,"b":2}');
+const result2 = _.safeJSONParse(null);
+
+console.log(result1); // Returns { a: 1, b: 2 }
+console.log(result2); // Returns {}
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');
+const result2 = _.safeParseInt('10.1234');
+const result3 = _.safeParseInt(null, -1);
+
+console.log(result1); // Returns 10
+console.log(result2); // Returns 10
+console.log(result3); // Returns -1
Return number format including comma symbol.
number::number
string
_.numberFormat(1234567); // Returns 1,234,567
numberFormat(1234567); // Returns 1,234,567
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'
+_.fileName('C:Temp\\file.mp3', true); // Returns 'file.mp3'
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'
+_.fileSize(250000000); // Returns '238.42 MB'
Returns only the extensions in the file path. If unknown, returns 'Unknown'.
filePath::string
string
_.fileExt('C:Temphello.txt'); // Returns 'txt'
+_.fileExt('this-is-file.mp3'); // Returns 'mp3'
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'
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
. The default value for fallback
is an empty object.
jsonString::any
fallback::object
object
const result1 = _.safeJSONParse('{"a":1,"b":2}');
+const result2 = _.safeJSONParse(null);
+
+console.log(result1); // Returns { a: 1, b: 2 }
+console.log(result2); // Returns {}
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');
+const result2 = _.safeParseInt('10.1234');
+const result3 = _.safeParseInt(null, -1);
+
+console.log(result1); // Returns 10
+console.log(result2); // Returns 10
+console.log(result3); // Returns -1
Returns a random number (Between min and max).
min::number
max::number
number
_.numRandom(1, 5); // Returns 1~5
+_.numRandom(10, 20); // Returns 10~20
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
+_.sum([1, 2, 3, 4]); // Returns 10
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
+_.mul([1, 2, 3, 4]); // Returns 24
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
+_.sub([1, 2, 3, 4]); // Returns -8
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
+_.div([100, 2, 2, 5]); // Returns 5
Returns a random number (Between min and max).
min::number
max::number
number
_.numRandom(1, 5); // Returns 1~5
+_.numRandom(10, 20); // Returns 10~20
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
+_.sum([1, 2, 3, 4]); // Returns 10
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
+_.mul([1, 2, 3, 4]); // Returns 24
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
+_.sub([1, 2, 3, 4]); // Returns -8
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
+_.div([100, 2, 2, 5]); // Returns 5
Sleep function using Promise.
milliseconds::number
Promise:boolean
await _.sleep(1000); // 1s
+
+_.sleep(5000).then(() => {
+ // continue
+});
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!']
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>
Sleep function using Promise.
milliseconds::number
Promise:boolean
await _.sleep(1000); // 1s
+
+_.sleep(5000).then(() => {
+ // continue
+});
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!']
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>
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'
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}'
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' }'
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 }]]
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
Dart:Namedobject
_.objToArray({
+ a: 1,
+ b: {
+ aa: 1,
+ bb: 2
+ },
+ c: 3
+});
+
+/*
+Returns:
+{
+ a: 1,
+ 'b.aa': 1,
+ 'b.bb': 2,
+ c: 3
+}
+ */
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: {} }
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 }
Merge two object data into one object. The key to this method is to compare the two objects and add the newly added key data, if any.
If the value is different from the existing key, it is replaced with the changed value, but not in the case of an array. However, if the arrays are the same length and the data type of the array is object, the new key is added by comparing the object keys again at the same array index for both objects.
You must specify the original value for the first argument and the object value containing the newly added key for the second argument.
obj::object
obj2::object
object|null
const result = objMergeNewKey(
+ {
+ a: 1,
+ b: {
+ a: 1
+ },
+ c: [1, 2]
+ },
+ {
+ b: {
+ b: 2
+ },
+ c: [3],
+ d: 4
+ }
+);
+
+console.log(result); // Returns { a: 1, b: { a: 1, b: 2 }, c: [1, 2], d: 4
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'
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}'
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' }'
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 }]]
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
Dart:Namedobject
_.objToArray({
+ a: 1,
+ b: {
+ aa: 1,
+ bb: 2
+ },
+ c: 3
+});
+
+/*
+Returns:
+{
+ a: 1,
+ 'b.aa': 1,
+ 'b.bb': 2,
+ c: 3
+}
+ */
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: {} }
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 }
Merge two object data into one object. The key to this method is to compare the two objects and add the newly added key data, if any.
If the value is different from the existing key, it is replaced with the changed value, but not in the case of an array. However, if the arrays are the same length and the data type of the array is object, the new key is added by comparing the object keys again at the same array index for both objects.
You must specify the original value for the first argument and the object value containing the newly added key for the second argument.
obj::object
obj2::object
object|null
const result = objMergeNewKey(
+ {
+ a: 1,
+ b: {
+ a: 1
+ },
+ c: [1, 2]
+ },
+ {
+ b: {
+ b: 2
+ },
+ c: [3],
+ d: 4
+ }
+);
+
+console.log(result); // Returns { a: 1, b: { a: 1, b: 2 }, c: [1, 2], d: 4
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'
+_.trim('H e l l o World'); // Returns 'H e l l o World'
trim(' Hello Wor ld '); // Returns 'Hello Wor ld'
+trim('H e l l o World'); // Returns 'H e l l o World'
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?
Dart:Namedstring
_.removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+_.removeSpecialChar('Hello-qsu, World!', ' -'); // Returns 'Hello-qsu World'
removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+removeSpecialChar('Hello-qsu, World!', exceptionCharacters: ' -'); // Returns 'Hello-qsu World'
Removes \\n
, \\r
characters or replaces them with specified characters.
str::string
replaceTo::string || ''
Dart:Namedstring
_.removeNewLine('ab\\ncd'); // Returns 'abcd'
+_.removeNewLine('ab\\r\\ncd', '-'); // Returns 'ab-cd'
removeNewLine('ab\\ncd'); // Returns 'abcd'
+removeNewLine('ab\\r\\ncd', replaceTo: '-'); // Returns 'ab-cd'
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'
+_.replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
replaceBetween('ab[c]d[e]f', '[', ']'); // Returns 'abdf'
+replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
Converts the first letter of the entire string to uppercase and returns.
str::string
string
_.capitalizeFirst('abcd'); // Returns 'Abcd'
capitalizeFirst('abcd'); // Returns 'Abcd'
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
Dart:Namedstring
_.capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+_.capitalizeEverySentence('hello!world', '!'); // Returns 'Hello!World'
capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+capitalizeEverySentence('hello!world', splitChar: '!'); // Returns 'Hello!World'
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
Dart:Namedstring
_.capitalizeEachWords('abcd'); // Returns 'Abcd'
capitalizeEachWords('abcd'); // Returns 'Abcd'
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
strCount('abcabc', 'a'); // Returns 2
Randomly shuffles the received string and returns it.
str::string
string
_.strShuffle('abcdefg'); // Returns 'bgafced'
strShuffle('abcdefg'); // Returns 'bgafced'
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?
Dart:Namedstring
_.strRandom(5); // Returns 'CHy2M'
strRandom(5); // Returns 'CHy2M'
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'
Truncates a long string to a specified length, optionally appending an ellipsis after the string.
str::string
length::number
ellipsis::string || ''
Dart:Namedstring
_.truncate('hello', 3); // Returns 'hel'
+_.truncate('hello', 2, '...'); // Returns 'he...'
truncate('hello', 3); // Returns 'hel'
+truncate('hello', 2, ellipsis: '...'); // Returns 'he...'
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 || '.'
Dart:Namedstring
_.truncateExpect('hello. this is test string.', 10, '.'); // Returns 'hello. this is test string.'
+_.truncateExpect('hello-this-is-test-string-bye', 14, '-'); // Returns 'hello-this-is-'
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']
+_.split('hello,js,world', ','); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', ',', '%'); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', [',', '%']); // Returns ['hello', 'js', 'world']
Remove duplicate characters from a given string and output only one.
str::string
string
_.strUnique('aaabbbcc'); // Returns 'abc'
Converts the given string to ascii code and returns it as an array.
str::string
number[]
_.strToAscii('12345'); // Returns [49, 50, 51, 52, 53]
Merges the given string argument with the first argument (the beginning of the URL), joining it so that the slash (/
) symbol is correctly included.
In Dart, accepts only one argument, organized as an List.
args::...any[]
(JavaScript)args::List<dynamic>
(Dart)string
_.urlJoin('https://example.com', 'hello', 'world'); // Returns 'https://example.com/hello/world'
urlJoin(['https://example.com', 'hello', 'world']); // Returns 'https://example.com/hello/world'
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'
+_.trim('H e l l o World'); // Returns 'H e l l o World'
trim(' Hello Wor ld '); // Returns 'Hello Wor ld'
+trim('H e l l o World'); // Returns 'H e l l o World'
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?
Dart:Namedstring
_.removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+_.removeSpecialChar('Hello-qsu, World!', ' -'); // Returns 'Hello-qsu World'
removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+removeSpecialChar('Hello-qsu, World!', exceptionCharacters: ' -'); // Returns 'Hello-qsu World'
Removes \\n
, \\r
characters or replaces them with specified characters.
str::string
replaceTo::string || ''
Dart:Namedstring
_.removeNewLine('ab\\ncd'); // Returns 'abcd'
+_.removeNewLine('ab\\r\\ncd', '-'); // Returns 'ab-cd'
removeNewLine('ab\\ncd'); // Returns 'abcd'
+removeNewLine('ab\\r\\ncd', replaceTo: '-'); // Returns 'ab-cd'
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'
+_.replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
replaceBetween('ab[c]d[e]f', '[', ']'); // Returns 'abdf'
+replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
Converts the first letter of the entire string to uppercase and returns.
str::string
string
_.capitalizeFirst('abcd'); // Returns 'Abcd'
capitalizeFirst('abcd'); // Returns 'Abcd'
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
Dart:Namedstring
_.capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+_.capitalizeEverySentence('hello!world', '!'); // Returns 'Hello!World'
capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+capitalizeEverySentence('hello!world', splitChar: '!'); // Returns 'Hello!World'
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
Dart:Namedstring
_.capitalizeEachWords('abcd'); // Returns 'Abcd'
capitalizeEachWords('abcd'); // Returns 'Abcd'
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
strCount('abcabc', 'a'); // Returns 2
Randomly shuffles the received string and returns it.
str::string
string
_.strShuffle('abcdefg'); // Returns 'bgafced'
strShuffle('abcdefg'); // Returns 'bgafced'
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?
Dart:Namedstring
_.strRandom(5); // Returns 'CHy2M'
strRandom(5); // Returns 'CHy2M'
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'
Truncates a long string to a specified length, optionally appending an ellipsis after the string.
str::string
length::number
ellipsis::string || ''
Dart:Namedstring
_.truncate('hello', 3); // Returns 'hel'
+_.truncate('hello', 2, '...'); // Returns 'he...'
truncate('hello', 3); // Returns 'hel'
+truncate('hello', 2, ellipsis: '...'); // Returns 'he...'
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 || '.'
Dart:Namedstring
_.truncateExpect('hello. this is test string.', 10, '.'); // Returns 'hello. this is test string.'
+_.truncateExpect('hello-this-is-test-string-bye', 14, '-'); // Returns 'hello-this-is-'
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']
+_.split('hello,js,world', ','); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', ',', '%'); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', [',', '%']); // Returns ['hello', 'js', 'world']
Remove duplicate characters from a given string and output only one.
str::string
string
_.strUnique('aaabbbcc'); // Returns 'abc'
Converts the given string to ascii code and returns it as an array.
str::string
number[]
_.strToAscii('12345'); // Returns [49, 50, 51, 52, 53]
Merges the given string argument with the first argument (the beginning of the URL), joining it so that the slash (/
) symbol is correctly included.
In Dart, accepts only one argument, organized as an List.
args::...any[]
(JavaScript)args::List<dynamic>
(Dart)string
_.urlJoin('https://example.com', 'hello', 'world'); // Returns 'https://example.com/hello/world'
urlJoin(['https://example.com', 'hello', 'world']); // Returns 'https://example.com/hello/world'
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
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
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
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
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
Returns true
if the given array is a two-dimensional array.
array::any[]
boolean
_.is2dArray([1]); // Returns false
+_.is2dArray([[1], [2]]); // Returns true
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
Dart:Namedboolean
_.contains('abc', 'a'); // Returns true
+_.contains('abc', 'd'); // Returns false
+_.contains('abc', ['a', 'd']); // Returns true
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
Dart:Namedboolean
_.between([10, 20], 10); // Returns false
+_.between([10, 20], 10, true); // Returns true
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
Checks if the given argument value is a valid email.
email::string
boolean
_.isEmail('abc@def.com'); // Returns true
Returns true
if the values given in the conditions
array are true at least minimumCount
times.
conditions::boolean[]
minimumCount::number
Dart:Namedboolean
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
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
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
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
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
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
Returns true
if the given array is a two-dimensional array.
array::any[]
boolean
_.is2dArray([1]); // Returns false
+_.is2dArray([[1], [2]]); // Returns true
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
Dart:Namedboolean
_.contains('abc', 'a'); // Returns true
+_.contains('abc', 'd'); // Returns false
+_.contains('abc', ['a', 'd']); // Returns true
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
Dart:Namedboolean
_.between([10, 20], 10); // Returns false
+_.between([10, 20], 10, true); // Returns true
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
Checks if the given argument value is a valid email.
email::string
boolean
_.isEmail('abc@def.com'); // Returns true
Returns true
if the values given in the conditions
array are true at least minimumCount
times.
conditions::boolean[]
minimumCount::number
Dart:Namedboolean
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
This method is only available in the qsu-web
(JavaScript) package.
isMatchPathname
You can check if the URL path in the first argument value is matched against the second set of rules. The matching rules can take a string or an array of strings, where both arguments are paths that start with /
. You can use wildcards (*
) in the rules. For example, user/*
would match all pages that start with /user
.
pathname::string
matcher::string|string[]
boolean
_.isMatchPathname('/user/login', '/admin'); // Returns false
+_.isMatchPathname('/user/login', '/user*'); // Returns true
+_.isMatchPathname('/user/login', ['/test', '/home/hello', '/user/*']); // Returns true
isBotAgent
Analyze the user agent value to determine if it's a bot for a search engine. Returns true
if it's a bot.
userAgent::string
boolean
_.isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); // Returns true
removeLocalePrefix
Removes the first-level path from a URL or pathname. Use this when you need a locale-free path in special cases in a URL that normally uses locale prefixes. For example, /en/hello
is converted to /hello
.
The first argument can be a URL or a pathname. When using a URL, include the protocol (for example, https://
). The second argument must contain at least one supported locale (e.g., en
, ['en', 'en', 'it', 'de']
).
pathname::string
matcher::string|string[]
boolean
_.removeLocalePrefix('/ko/user/login', ['ko', 'en']); // Returns '/user/login'
+_.removeLocalePrefix('https://qsu.cdget.com/ko/user/login', ['ko', 'en']); // Returns 'https://qsu.cdget.com/user/login'
license
Returns text in a specific license format based on the author information of the given argument. The argument uses the Object type.
options::LicenseOption{ author: string, email: string?, yearStart: string|number, yearEnd: string?, htmlBr: boolean?, type: 'mit' | 'apache20' }
string
_.license({
+ holder: 'example',
+ email: 'example@example.com',
+ yearStart: 2020,
+ yearEnd: 2021,
+ htmlBr: true
+});
This method is only available in the qsu-web
(JavaScript) package.
isMatchPathname
You can check if the URL path in the first argument value is matched against the second set of rules. The matching rules can take a string or an array of strings, where both arguments are paths that start with /
. You can use wildcards (*
) in the rules. For example, user/*
would match all pages that start with /user
.
pathname::string
matcher::string|string[]
boolean
_.isMatchPathname('/user/login', '/admin'); // Returns false
+_.isMatchPathname('/user/login', '/user*'); // Returns true
+_.isMatchPathname('/user/login', ['/test', '/home/hello', '/user/*']); // Returns true
isBotAgent
Analyze the user agent value to determine if it's a bot for a search engine. Returns true
if it's a bot.
userAgent::string
boolean
_.isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); // Returns true
removeLocalePrefix
Removes the first-level path from a URL or pathname. Use this when you need a locale-free path in special cases in a URL that normally uses locale prefixes. For example, /en/hello
is converted to /hello
.
The first argument can be a URL or a pathname. When using a URL, include the protocol (for example, https://
). The second argument must contain at least one supported locale (e.g., en
, ['en', 'en', 'it', 'de']
).
pathname::string
matcher::string|string[]
boolean
_.removeLocalePrefix('/ko/user/login', ['ko', 'en']); // Returns '/user/login'
+_.removeLocalePrefix('https://qsu.cdget.com/ko/user/login', ['ko', 'en']); // Returns 'https://qsu.cdget.com/user/login'
license
Returns text in a specific license format based on the author information of the given argument. The argument uses the Object type.
options::LicenseOption{ author: string, email: string?, yearStart: string|number, yearEnd: string?, htmlBr: boolean?, type: 'mit' | 'apache20' }
string
_.license({
+ holder: 'example',
+ email: 'example@example.com',
+ yearStart: 2020,
+ yearEnd: 2021,
+ htmlBr: true
+});
qsu
package no longer uses classes, so if you want to import the entire module at once, you must use something like import * as _ from 'qsu''
. (_
-> * as _
)objectTo1d
method have been renamed to objTo1d
md5
, sha1
, and sha256
methods have been renamed to md5Hash
, sha1Hash
, and sha256Hash
.objMergeNewKey
: Add objMergeNewKey
methodisObject
: 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 methodqsu
package no longer uses classes, so if you want to import the entire module at once, you must use something like import * as _ from 'qsu''
. (_
-> * as _
)objectTo1d
method have been renamed to objTo1d
md5
, sha1
, and sha256
methods have been renamed to md5Hash
, sha1Hash
, and sha256Hash
.objMergeNewKey
: Add objMergeNewKey
methodisObject
: 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 methodQsu requires Dart 3.x
or higher. If you are using Flutter, you must be using Flutter version 3.10.x or later.
After configuring the dart environment, you can simply run the following command:
$ dart pub add qsu
$ flutter pub add qsu
You can import the following code manually or automatically to bring up the QSU utility
import 'package:qsu/qsu.dart';
To learn more about utility functions, browse the API documentation.
',10))])}const f=e(d,[["render",u]]);export{y as __pageData,f as default}; diff --git a/assets/getting-started_installation-dart.md.CnLcXnNJ.lean.js b/assets/getting-started_installation-dart.md.CnLcXnNJ.lean.js new file mode 100644 index 0000000..ada798c --- /dev/null +++ b/assets/getting-started_installation-dart.md.CnLcXnNJ.lean.js @@ -0,0 +1 @@ +import{_ as e,c as n,j as t,a as s,G as l,a2 as o,B as r,o as h}from"./chunks/framework.DPuwY6B9.js";const y=JSON.parse('{"title":"Installation Dart","description":"","frontmatter":{"title":"Installation Dart","order":2},"headers":[],"relativePath":"getting-started/installation-dart.md","filePath":"en/getting-started/installation-dart.md","lastUpdated":1727327012000}'),d={name:"getting-started/installation-dart.md"},p={id:"installation",tabindex:"-1"};function u(k,a,c,g,F,b){const i=r("Badge");return h(),n("div",null,[t("h1",p,[a[0]||(a[0]=s("Installation ")),l(i,{type:"info",text:"Dart"}),a[1]||(a[1]=s()),a[2]||(a[2]=t("a",{class:"header-anchor",href:"#installation","aria-label":'Permalink to "InstallationQsu requires Dart 3.x
or higher. If you are using Flutter, you must be using Flutter version 3.10.x or later.
After configuring the dart environment, you can simply run the following command:
$ dart pub add qsu
$ flutter pub add qsu
You can import the following code manually or automatically to bring up the QSU utility
import 'package:qsu/qsu.dart';
To learn more about utility functions, browse the API documentation.
',10))])}const f=e(d,[["render",u]]);export{y as __pageData,f as default}; diff --git a/assets/getting-started_installation-javascript.md.4KwEaLCs.js b/assets/getting-started_installation-javascript.md.4KwEaLCs.js new file mode 100644 index 0000000..eb15778 --- /dev/null +++ b/assets/getting-started_installation-javascript.md.4KwEaLCs.js @@ -0,0 +1,21 @@ +import{_ as t,c as l,j as i,a,G as p,a2 as e,B as h,o as k}from"./chunks/framework.DPuwY6B9.js";const C=JSON.parse('{"title":"Installation JavaScript","description":"","frontmatter":{"title":"Installation JavaScript","order":1},"headers":[],"relativePath":"getting-started/installation-javascript.md","filePath":"en/getting-started/installation-javascript.md","lastUpdated":1733374404000}'),r={name:"getting-started/installation-javascript.md"},d={id:"installation",tabindex:"-1"};function o(g,s,E,F,y,c){const n=h("Badge");return k(),l("div",null,[i("h1",d,[s[0]||(s[0]=a("Installation ")),p(n,{type:"tip",text:"JavaScript"}),s[1]||(s[1]=a()),s[2]||(s[2]=i("a",{class:"header-anchor",href:"#installation","aria-label":'Permalink to "InstallationQsu requires Node.js 18.x
or higher, and the repository is serviced through NPM.
Qsu is ESM-only. You must use import
instead of require
to load the module. There are workarounds available for CommonJS, but we recommend using ESM based on recent JavaScript trends.
After configuring the node environment, you can simply run the following command.
# via npm
+$ npm install qsu
+$ npm install qsu-web # (Optional) When using the Add-on for Web
+
+# via yarn
+$ yarn add qsu
+$ yarn add qsu-web # (Optional) When using the Add-on for Web
+
+# via pnpm
+$ pnpm install qsu
+$ pnpm install qsu-web # (Optional) When using the Add-on for Web
In general, you can partially import and use each function as shown below.
import { today, strCount } from 'qsu';
+
+function main() {
+ console.log(today()); // '20xx-xx-xx'
+ console.log(strCount('123412341234', '1')); // 3
+}
You can use methods with underscore (_
) symbols to separate code and modules, as shown below. We recommend using partial imports unless there are special cases.
import * as _ from 'qsu';
+
+function main() {
+ console.log(_.today()); // '20xx-xx-xx'
+ console.log(_.strCount('123412341234', '1')); // 3
+}
Qsu requires Node.js 18.x
or higher, and the repository is serviced through NPM.
Qsu is ESM-only. You must use import
instead of require
to load the module. There are workarounds available for CommonJS, but we recommend using ESM based on recent JavaScript trends.
After configuring the node environment, you can simply run the following command.
# via npm
+$ npm install qsu
+$ npm install qsu-web # (Optional) When using the Add-on for Web
+
+# via yarn
+$ yarn add qsu
+$ yarn add qsu-web # (Optional) When using the Add-on for Web
+
+# via pnpm
+$ pnpm install qsu
+$ pnpm install qsu-web # (Optional) When using the Add-on for Web
In general, you can partially import and use each function as shown below.
import { today, strCount } from 'qsu';
+
+function main() {
+ console.log(today()); // '20xx-xx-xx'
+ console.log(strCount('123412341234', '1')); // 3
+}
You can use methods with underscore (_
) symbols to separate code and modules, as shown below. We recommend using partial imports unless there are special cases.
import * as _ from 'qsu';
+
+function main() {
+ console.log(_.today()); // '20xx-xx-xx'
+ console.log(_.strCount('123412341234', '1')); // 3
+}
Shuffle the order of the given array and return.
array::any[]
any[]
_.arrShuffle([1, 2, 3, 4]); // Returns [4, 2, 3, 1]
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]
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]
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]]
Returns the average of all numeric values in an array.
array::number[]
number
_.average([1, 5, 15, 50]); // Returns 17.75
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]
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]
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 }]
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 }
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'
+ }
+]
+*/
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']
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']]
Shuffle the order of the given array and return.
array::any[]
any[]
_.arrShuffle([1, 2, 3, 4]); // Returns [4, 2, 3, 1]
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]
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]
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]]
Returns the average of all numeric values in an array.
array::number[]
number
_.average([1, 5, 15, 50]); // Returns 17.75
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]
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]
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 }]
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 }
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'
+ }
+]
+*/
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']
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 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 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');
Returns a random string hash of the ObjectId format (primarily utilized by MongoDB).
No parameters required
string
_.objectId(); // Returns '651372605b49507aea707488'
Converts String data to md5 hash value and returns it.
str::string
string
_.md5Hash('test'); // Returns '098f6bcd4621d373cade4e832627b4f6'
Converts String data to sha1 hash value and returns it.
str::string
string
_.sha1Hash('test'); // Returns 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
Converts String data to sha256 hash value and returns it.
str::string
string
_.sha256Hash('test'); // Returns '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
Base64-encode the given string.
str::string
string
_.encodeBase64('this is test'); // Returns 'dGhpcyBpcyB0ZXN0'
Decodes an encoded base64 string to a plain string.
encodedStr::string
string
_.decodeBase64('dGhpcyBpcyB0ZXN0'); // Returns 'this is test'
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
+_.strToNumberHash('Hello'); // Returns 69609650
+_.strToNumberHash('hello'); // Returns 99162322
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 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');
Returns a random string hash of the ObjectId format (primarily utilized by MongoDB).
No parameters required
string
_.objectId(); // Returns '651372605b49507aea707488'
Converts String data to md5 hash value and returns it.
str::string
string
_.md5Hash('test'); // Returns '098f6bcd4621d373cade4e832627b4f6'
Converts String data to sha1 hash value and returns it.
str::string
string
_.sha1Hash('test'); // Returns 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
Converts String data to sha256 hash value and returns it.
str::string
string
_.sha256Hash('test'); // Returns '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
Base64-encode the given string.
str::string
string
_.encodeBase64('this is test'); // Returns 'dGhpcyBpcyB0ZXN0'
Decodes an encoded base64 string to a plain string.
encodedStr::string
string
_.decodeBase64('dGhpcyBpcyB0ZXN0'); // Returns 'this is test'
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
+_.strToNumberHash('Hello'); // Returns 69609650
+_.strToNumberHash('hello'); // Returns 99162322
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
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
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
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'
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'
+ ]
+ */
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
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
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
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'
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'
+ ]
+ */
Return number format including comma symbol.
number::number
string
_.numberFormat(1234567); // Returns 1,234,567
numberFormat(1234567); // Returns 1,234,567
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'
+_.fileName('C:Temp\\file.mp3', true); // Returns 'file.mp3'
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'
+_.fileSize(250000000); // Returns '238.42 MB'
Returns only the extensions in the file path. If unknown, returns 'Unknown'.
filePath::string
string
_.fileExt('C:Temphello.txt'); // Returns 'txt'
+_.fileExt('this-is-file.mp3'); // Returns 'mp3'
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'
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
. The default value for fallback
is an empty object.
jsonString::any
fallback::object
object
const result1 = _.safeJSONParse('{"a":1,"b":2}');
+const result2 = _.safeJSONParse(null);
+
+console.log(result1); // Returns { a: 1, b: 2 }
+console.log(result2); // Returns {}
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');
+const result2 = _.safeParseInt('10.1234');
+const result3 = _.safeParseInt(null, -1);
+
+console.log(result1); // Returns 10
+console.log(result2); // Returns 10
+console.log(result3); // Returns -1
Return number format including comma symbol.
number::number
string
_.numberFormat(1234567); // Returns 1,234,567
numberFormat(1234567); // Returns 1,234,567
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'
+_.fileName('C:Temp\\file.mp3', true); // Returns 'file.mp3'
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'
+_.fileSize(250000000); // Returns '238.42 MB'
Returns only the extensions in the file path. If unknown, returns 'Unknown'.
filePath::string
string
_.fileExt('C:Temphello.txt'); // Returns 'txt'
+_.fileExt('this-is-file.mp3'); // Returns 'mp3'
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'
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
. The default value for fallback
is an empty object.
jsonString::any
fallback::object
object
const result1 = _.safeJSONParse('{"a":1,"b":2}');
+const result2 = _.safeJSONParse(null);
+
+console.log(result1); // Returns { a: 1, b: 2 }
+console.log(result2); // Returns {}
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');
+const result2 = _.safeParseInt('10.1234');
+const result3 = _.safeParseInt(null, -1);
+
+console.log(result1); // Returns 10
+console.log(result2); // Returns 10
+console.log(result3); // Returns -1
Returns a random number (Between min and max).
min::number
max::number
number
_.numRandom(1, 5); // Returns 1~5
+_.numRandom(10, 20); // Returns 10~20
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
+_.sum([1, 2, 3, 4]); // Returns 10
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
+_.mul([1, 2, 3, 4]); // Returns 24
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
+_.sub([1, 2, 3, 4]); // Returns -8
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
+_.div([100, 2, 2, 5]); // Returns 5
Returns a random number (Between min and max).
min::number
max::number
number
_.numRandom(1, 5); // Returns 1~5
+_.numRandom(10, 20); // Returns 10~20
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
+_.sum([1, 2, 3, 4]); // Returns 10
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
+_.mul([1, 2, 3, 4]); // Returns 24
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
+_.sub([1, 2, 3, 4]); // Returns -8
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
+_.div([100, 2, 2, 5]); // Returns 5
Sleep function using Promise.
milliseconds::number
Promise:boolean
await _.sleep(1000); // 1s
+
+_.sleep(5000).then(() => {
+ // continue
+});
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!']
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>
Sleep function using Promise.
milliseconds::number
Promise:boolean
await _.sleep(1000); // 1s
+
+_.sleep(5000).then(() => {
+ // continue
+});
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!']
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>
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'
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}'
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' }'
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 }]]
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
Dart:Namedobject
_.objToArray({
+ a: 1,
+ b: {
+ aa: 1,
+ bb: 2
+ },
+ c: 3
+});
+
+/*
+Returns:
+{
+ a: 1,
+ 'b.aa': 1,
+ 'b.bb': 2,
+ c: 3
+}
+ */
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: {} }
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 }
Merge two object data into one object. The key to this method is to compare the two objects and add the newly added key data, if any.
If the value is different from the existing key, it is replaced with the changed value, but not in the case of an array. However, if the arrays are the same length and the data type of the array is object, the new key is added by comparing the object keys again at the same array index for both objects.
You must specify the original value for the first argument and the object value containing the newly added key for the second argument.
obj::object
obj2::object
object|null
const result = objMergeNewKey(
+ {
+ a: 1,
+ b: {
+ a: 1
+ },
+ c: [1, 2]
+ },
+ {
+ b: {
+ b: 2
+ },
+ c: [3],
+ d: 4
+ }
+);
+
+console.log(result); // Returns { a: 1, b: { a: 1, b: 2 }, c: [1, 2], d: 4
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'
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}'
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' }'
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 }]]
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
Dart:Namedobject
_.objToArray({
+ a: 1,
+ b: {
+ aa: 1,
+ bb: 2
+ },
+ c: 3
+});
+
+/*
+Returns:
+{
+ a: 1,
+ 'b.aa': 1,
+ 'b.bb': 2,
+ c: 3
+}
+ */
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: {} }
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 }
Merge two object data into one object. The key to this method is to compare the two objects and add the newly added key data, if any.
If the value is different from the existing key, it is replaced with the changed value, but not in the case of an array. However, if the arrays are the same length and the data type of the array is object, the new key is added by comparing the object keys again at the same array index for both objects.
You must specify the original value for the first argument and the object value containing the newly added key for the second argument.
obj::object
obj2::object
object|null
const result = objMergeNewKey(
+ {
+ a: 1,
+ b: {
+ a: 1
+ },
+ c: [1, 2]
+ },
+ {
+ b: {
+ b: 2
+ },
+ c: [3],
+ d: 4
+ }
+);
+
+console.log(result); // Returns { a: 1, b: { a: 1, b: 2 }, c: [1, 2], d: 4
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'
+_.trim('H e l l o World'); // Returns 'H e l l o World'
trim(' Hello Wor ld '); // Returns 'Hello Wor ld'
+trim('H e l l o World'); // Returns 'H e l l o World'
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?
Dart:Namedstring
_.removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+_.removeSpecialChar('Hello-qsu, World!', ' -'); // Returns 'Hello-qsu World'
removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+removeSpecialChar('Hello-qsu, World!', exceptionCharacters: ' -'); // Returns 'Hello-qsu World'
Removes \\n
, \\r
characters or replaces them with specified characters.
str::string
replaceTo::string || ''
Dart:Namedstring
_.removeNewLine('ab\\ncd'); // Returns 'abcd'
+_.removeNewLine('ab\\r\\ncd', '-'); // Returns 'ab-cd'
removeNewLine('ab\\ncd'); // Returns 'abcd'
+removeNewLine('ab\\r\\ncd', replaceTo: '-'); // Returns 'ab-cd'
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'
+_.replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
replaceBetween('ab[c]d[e]f', '[', ']'); // Returns 'abdf'
+replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
Converts the first letter of the entire string to uppercase and returns.
str::string
string
_.capitalizeFirst('abcd'); // Returns 'Abcd'
capitalizeFirst('abcd'); // Returns 'Abcd'
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
Dart:Namedstring
_.capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+_.capitalizeEverySentence('hello!world', '!'); // Returns 'Hello!World'
capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+capitalizeEverySentence('hello!world', splitChar: '!'); // Returns 'Hello!World'
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
Dart:Namedstring
_.capitalizeEachWords('abcd'); // Returns 'Abcd'
capitalizeEachWords('abcd'); // Returns 'Abcd'
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
strCount('abcabc', 'a'); // Returns 2
Randomly shuffles the received string and returns it.
str::string
string
_.strShuffle('abcdefg'); // Returns 'bgafced'
strShuffle('abcdefg'); // Returns 'bgafced'
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?
Dart:Namedstring
_.strRandom(5); // Returns 'CHy2M'
strRandom(5); // Returns 'CHy2M'
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'
Truncates a long string to a specified length, optionally appending an ellipsis after the string.
str::string
length::number
ellipsis::string || ''
Dart:Namedstring
_.truncate('hello', 3); // Returns 'hel'
+_.truncate('hello', 2, '...'); // Returns 'he...'
truncate('hello', 3); // Returns 'hel'
+truncate('hello', 2, ellipsis: '...'); // Returns 'he...'
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 || '.'
Dart:Namedstring
_.truncateExpect('hello. this is test string.', 10, '.'); // Returns 'hello. this is test string.'
+_.truncateExpect('hello-this-is-test-string-bye', 14, '-'); // Returns 'hello-this-is-'
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']
+_.split('hello,js,world', ','); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', ',', '%'); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', [',', '%']); // Returns ['hello', 'js', 'world']
Remove duplicate characters from a given string and output only one.
str::string
string
_.strUnique('aaabbbcc'); // Returns 'abc'
Converts the given string to ascii code and returns it as an array.
str::string
number[]
_.strToAscii('12345'); // Returns [49, 50, 51, 52, 53]
Merges the given string argument with the first argument (the beginning of the URL), joining it so that the slash (/
) symbol is correctly included.
In Dart, accepts only one argument, organized as an List.
args::...any[]
(JavaScript)args::List<dynamic>
(Dart)string
_.urlJoin('https://example.com', 'hello', 'world'); // Returns 'https://example.com/hello/world'
urlJoin(['https://example.com', 'hello', 'world']); // Returns 'https://example.com/hello/world'
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'
+_.trim('H e l l o World'); // Returns 'H e l l o World'
trim(' Hello Wor ld '); // Returns 'Hello Wor ld'
+trim('H e l l o World'); // Returns 'H e l l o World'
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?
Dart:Namedstring
_.removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+_.removeSpecialChar('Hello-qsu, World!', ' -'); // Returns 'Hello-qsu World'
removeSpecialChar('Hello-qsu, World!'); // Returns 'HelloqsuWorld'
+removeSpecialChar('Hello-qsu, World!', exceptionCharacters: ' -'); // Returns 'Hello-qsu World'
Removes \\n
, \\r
characters or replaces them with specified characters.
str::string
replaceTo::string || ''
Dart:Namedstring
_.removeNewLine('ab\\ncd'); // Returns 'abcd'
+_.removeNewLine('ab\\r\\ncd', '-'); // Returns 'ab-cd'
removeNewLine('ab\\ncd'); // Returns 'abcd'
+removeNewLine('ab\\r\\ncd', replaceTo: '-'); // Returns 'ab-cd'
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'
+_.replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
replaceBetween('ab[c]d[e]f', '[', ']'); // Returns 'abdf'
+replaceBetween('abcd:replace:', ':', ':', 'e'); // Returns 'abcde'
Converts the first letter of the entire string to uppercase and returns.
str::string
string
_.capitalizeFirst('abcd'); // Returns 'Abcd'
capitalizeFirst('abcd'); // Returns 'Abcd'
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
Dart:Namedstring
_.capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+_.capitalizeEverySentence('hello!world', '!'); // Returns 'Hello!World'
capitalizeEverySentence('hello. world. hi.'); // Returns 'Hello. World. Hi.'
+capitalizeEverySentence('hello!world', splitChar: '!'); // Returns 'Hello!World'
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
Dart:Namedstring
_.capitalizeEachWords('abcd'); // Returns 'Abcd'
capitalizeEachWords('abcd'); // Returns 'Abcd'
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
strCount('abcabc', 'a'); // Returns 2
Randomly shuffles the received string and returns it.
str::string
string
_.strShuffle('abcdefg'); // Returns 'bgafced'
strShuffle('abcdefg'); // Returns 'bgafced'
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?
Dart:Namedstring
_.strRandom(5); // Returns 'CHy2M'
strRandom(5); // Returns 'CHy2M'
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'
Truncates a long string to a specified length, optionally appending an ellipsis after the string.
str::string
length::number
ellipsis::string || ''
Dart:Namedstring
_.truncate('hello', 3); // Returns 'hel'
+_.truncate('hello', 2, '...'); // Returns 'he...'
truncate('hello', 3); // Returns 'hel'
+truncate('hello', 2, ellipsis: '...'); // Returns 'he...'
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 || '.'
Dart:Namedstring
_.truncateExpect('hello. this is test string.', 10, '.'); // Returns 'hello. this is test string.'
+_.truncateExpect('hello-this-is-test-string-bye', 14, '-'); // Returns 'hello-this-is-'
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']
+_.split('hello,js,world', ','); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', ',', '%'); // Returns ['hello', 'js', 'world']
+_.split('hello%js,world', [',', '%']); // Returns ['hello', 'js', 'world']
Remove duplicate characters from a given string and output only one.
str::string
string
_.strUnique('aaabbbcc'); // Returns 'abc'
Converts the given string to ascii code and returns it as an array.
str::string
number[]
_.strToAscii('12345'); // Returns [49, 50, 51, 52, 53]
Merges the given string argument with the first argument (the beginning of the URL), joining it so that the slash (/
) symbol is correctly included.
In Dart, accepts only one argument, organized as an List.
args::...any[]
(JavaScript)args::List<dynamic>
(Dart)string
_.urlJoin('https://example.com', 'hello', 'world'); // Returns 'https://example.com/hello/world'
urlJoin(['https://example.com', 'hello', 'world']); // Returns 'https://example.com/hello/world'
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
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
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
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
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
Returns true
if the given array is a two-dimensional array.
array::any[]
boolean
_.is2dArray([1]); // Returns false
+_.is2dArray([[1], [2]]); // Returns true
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
Dart:Namedboolean
_.contains('abc', 'a'); // Returns true
+_.contains('abc', 'd'); // Returns false
+_.contains('abc', ['a', 'd']); // Returns true
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
Dart:Namedboolean
_.between([10, 20], 10); // Returns false
+_.between([10, 20], 10, true); // Returns true
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
Checks if the given argument value is a valid email.
email::string
boolean
_.isEmail('abc@def.com'); // Returns true
Returns true
if the values given in the conditions
array are true at least minimumCount
times.
conditions::boolean[]
minimumCount::number
Dart:Namedboolean
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
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
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
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
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
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
Returns true
if the given array is a two-dimensional array.
array::any[]
boolean
_.is2dArray([1]); // Returns false
+_.is2dArray([[1], [2]]); // Returns true
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
Dart:Namedboolean
_.contains('abc', 'a'); // Returns true
+_.contains('abc', 'd'); // Returns false
+_.contains('abc', ['a', 'd']); // Returns true
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
Dart:Namedboolean
_.between([10, 20], 10); // Returns false
+_.between([10, 20], 10, true); // Returns true
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
Checks if the given argument value is a valid email.
email::string
boolean
_.isEmail('abc@def.com'); // Returns true
Returns true
if the values given in the conditions
array are true at least minimumCount
times.
conditions::boolean[]
minimumCount::number
Dart:Namedboolean
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
This method is only available in the qsu-web
(JavaScript) package.
isMatchPathname
처음 인자값의 URL 경로가 두번째 rule set에 매칭되는지 확인할 수 있습니다. 매칭 규칙은 string 또는 string으로 구성된 배열을 사용할 수 있으며, 두 인자 모두 경로는 /
으로 시작합니다. 규칙에는 와일드카드(*
)를 사용할 수 있습니다. 예를 들어 user/*
인 경우 /user
로 시작되는 페이지가 모두 해당됩니다.
pathname::string
matcher::string|string[]
boolean
_.isMatchPathname('/user/login', '/admin'); // Returns false
+_.isMatchPathname('/user/login', '/user*'); // Returns true
+_.isMatchPathname('/user/login', ['/test', '/home/hello', '/user/*']); // Returns true
isBotAgent
Analyze the user agent value to determine if it's a bot for a search engine. Returns true
if it's a bot.
userAgent::string
boolean
_.isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); // Returns true
removeLocalePrefix
URL 또는 pathname에서 1단계 경로를 제거합니다. 일반적으로 로캐일 프리픽스를 사용하는 URL에서 특수한 경우 로캐일 없는 경로가 필요할 때 사용합니다. 예를 들어, /en/hello
는 /hello
와 같이 변환됩니다.
첫번째 인자에는 URL이나 pathname을 넣을 수 있습니다. URL을 사용할 때는 프로토콜(예: https://
)을 포함합니다. 두번째 인자에는 지원하는 로캐일이 하나 이상 포함되어야 합니다. (예: en
, ['ko', 'en', 'it', 'de']
)
pathname::string
matcher::string|string[]
boolean
_.removeLocalePrefix('/ko/user/login', ['ko', 'en']); // Returns '/user/login'
+_.removeLocalePrefix('https://qsu.cdget.com/ko/user/login', ['ko', 'en']); // Returns 'https://qsu.cdget.com/user/login'
license
Returns text in a specific license format based on the author information of the given argument. The argument uses the Object type.
options::LicenseOption{ author: string, email: string?, yearStart: string|number, yearEnd: string?, htmlBr: boolean?, type: 'mit' | 'apache20' }
string
_.license({
+ holder: 'example',
+ email: 'example@example.com',
+ yearStart: 2020,
+ yearEnd: 2021,
+ htmlBr: true
+});
This method is only available in the qsu-web
(JavaScript) package.
isMatchPathname
처음 인자값의 URL 경로가 두번째 rule set에 매칭되는지 확인할 수 있습니다. 매칭 규칙은 string 또는 string으로 구성된 배열을 사용할 수 있으며, 두 인자 모두 경로는 /
으로 시작합니다. 규칙에는 와일드카드(*
)를 사용할 수 있습니다. 예를 들어 user/*
인 경우 /user
로 시작되는 페이지가 모두 해당됩니다.
pathname::string
matcher::string|string[]
boolean
_.isMatchPathname('/user/login', '/admin'); // Returns false
+_.isMatchPathname('/user/login', '/user*'); // Returns true
+_.isMatchPathname('/user/login', ['/test', '/home/hello', '/user/*']); // Returns true
isBotAgent
Analyze the user agent value to determine if it's a bot for a search engine. Returns true
if it's a bot.
userAgent::string
boolean
_.isBotAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); // Returns true
removeLocalePrefix
URL 또는 pathname에서 1단계 경로를 제거합니다. 일반적으로 로캐일 프리픽스를 사용하는 URL에서 특수한 경우 로캐일 없는 경로가 필요할 때 사용합니다. 예를 들어, /en/hello
는 /hello
와 같이 변환됩니다.
첫번째 인자에는 URL이나 pathname을 넣을 수 있습니다. URL을 사용할 때는 프로토콜(예: https://
)을 포함합니다. 두번째 인자에는 지원하는 로캐일이 하나 이상 포함되어야 합니다. (예: en
, ['ko', 'en', 'it', 'de']
)
pathname::string
matcher::string|string[]
boolean
_.removeLocalePrefix('/ko/user/login', ['ko', 'en']); // Returns '/user/login'
+_.removeLocalePrefix('https://qsu.cdget.com/ko/user/login', ['ko', 'en']); // Returns 'https://qsu.cdget.com/user/login'
license
Returns text in a specific license format based on the author information of the given argument. The argument uses the Object type.
options::LicenseOption{ author: string, email: string?, yearStart: string|number, yearEnd: string?, htmlBr: boolean?, type: 'mit' | 'apache20' }
string
_.license({
+ holder: 'example',
+ email: 'example@example.com',
+ yearStart: 2020,
+ yearEnd: 2021,
+ htmlBr: true
+});
Qsu에는 Dart 3.x
이상이 필요합니다. Flutter를 사용 중인 경우 Flutter 버전 3.10.x 이상을 사용 중이어야 합니다.
Dart 환경을 구성한 후 다음 명령을 실행하면 됩니다:
$ dart pub add qsu
$ flutter pub add qsu
다음 코드를 수동 또는 자동으로 가져와서 QSU 유틸리티를 불러올 수 있습니다.
import 'package:qsu/qsu.dart';
유틸리티 기능에 대해 자세히 알아보려면 API 설명서를 참조하세요.
',10))])}const f=i(o,[["render",k]]);export{y as __pageData,f as default}; diff --git a/assets/ko_getting-started_installation-dart.md.BbNi2rOX.lean.js b/assets/ko_getting-started_installation-dart.md.BbNi2rOX.lean.js new file mode 100644 index 0000000..409c266 --- /dev/null +++ b/assets/ko_getting-started_installation-dart.md.BbNi2rOX.lean.js @@ -0,0 +1 @@ +import{_ as i,c as n,j as t,a as s,G as l,a2 as r,B as d,o as p}from"./chunks/framework.DPuwY6B9.js";const y=JSON.parse('{"title":"설치 Dart","description":"","frontmatter":{"title":"설치 Dart","order":2},"headers":[],"relativePath":"ko/getting-started/installation-dart.md","filePath":"ko/getting-started/installation-dart.md","lastUpdated":1727326645000}'),o={name:"ko/getting-started/installation-dart.md"},h={id:"설치",tabindex:"-1"};function k(c,a,g,u,F,b){const e=d("Badge");return p(),n("div",null,[t("h1",h,[a[0]||(a[0]=s("설치 ")),l(e,{type:"info",text:"Dart"}),a[1]||(a[1]=s()),a[2]||(a[2]=t("a",{class:"header-anchor",href:"#설치","aria-label":'Permalink to "설치Qsu에는 Dart 3.x
이상이 필요합니다. Flutter를 사용 중인 경우 Flutter 버전 3.10.x 이상을 사용 중이어야 합니다.
Dart 환경을 구성한 후 다음 명령을 실행하면 됩니다:
$ dart pub add qsu
$ flutter pub add qsu
다음 코드를 수동 또는 자동으로 가져와서 QSU 유틸리티를 불러올 수 있습니다.
import 'package:qsu/qsu.dart';
유틸리티 기능에 대해 자세히 알아보려면 API 설명서를 참조하세요.
',10))])}const f=i(o,[["render",k]]);export{y as __pageData,f as default}; diff --git a/assets/ko_getting-started_installation-javascript.md.C7W7Rt-G.js b/assets/ko_getting-started_installation-javascript.md.C7W7Rt-G.js new file mode 100644 index 0000000..27592f9 --- /dev/null +++ b/assets/ko_getting-started_installation-javascript.md.C7W7Rt-G.js @@ -0,0 +1,20 @@ +import{_ as t,c as p,j as i,a,G as l,a2 as h,B as e,o as k}from"./chunks/framework.DPuwY6B9.js";const B=JSON.parse('{"title":"설치 JavaScript","description":"","frontmatter":{"title":"설치 JavaScript","order":1},"headers":[],"relativePath":"ko/getting-started/installation-javascript.md","filePath":"ko/getting-started/installation-javascript.md","lastUpdated":1733374404000}'),r={name:"ko/getting-started/installation-javascript.md"},d={id:"설치",tabindex:"-1"};function g(o,s,E,F,c,y){const n=e("Badge");return k(),p("div",null,[i("h1",d,[s[0]||(s[0]=a("설치 ")),l(n,{type:"tip",text:"JavaScript"}),s[1]||(s[1]=a()),s[2]||(s[2]=i("a",{class:"header-anchor",href:"#설치","aria-label":'Permalink to "설치Qsu는 Node.js 18.x
이상이 필요하며, 리포지토리는 NPM 패키지 관리자에서 서비스됩니다.
Qsu는 ESM 전용입니다. 모듈을 로드하려면 require
대신 import
를 사용해야 합니다. CommonJS에 사용할 수 있는 해결 방법이 있지만 최근 JavaScript 트렌드에 따라 ESM을 사용하는 것이 좋습니다.
Node.js 환경을 구성한 후 다음 명령을 실행하면 됩니다:
# via npm
+$ npm install qsu
+$ npm install qsu-web # (선택적) Web용 추가 유틸을 사용할 때
+
+# via yarn
+$ yarn add qsu
+$ yarn add qsu-web # (선택적) Web용 추가 유틸을 사용할 때
+
+# via pnpm
+$ pnpm install qsu
+$ pnpm install qsu-web # (선택적) Web용 추가 유틸을 사용할 때
일반적으로 각각의 함수를 아래와 같이 부분적으로 import하여 사용할 수 있습니다.
import { today, strCount } from 'qsu';
+
+function main() {
+ console.log(today()); // '20xx-xx-xx'
+ console.log(strCount('123412341234', '1')); // 3
+}
코드와 모듈의 구분을 위해 아래처럼 언더스코어(_
)기호 등을 사용하여 메소드를 사용할 수 있습니다. 특별한 경우가 아니면 부분 가져오기를 사용하는 것을 권장합니다.
import _ from 'qsu';
+
+function main() {
+ console.log(_.today()); // '20xx-xx-xx'
+}
Qsu는 Node.js 18.x
이상이 필요하며, 리포지토리는 NPM 패키지 관리자에서 서비스됩니다.
Qsu는 ESM 전용입니다. 모듈을 로드하려면 require
대신 import
를 사용해야 합니다. CommonJS에 사용할 수 있는 해결 방법이 있지만 최근 JavaScript 트렌드에 따라 ESM을 사용하는 것이 좋습니다.
Node.js 환경을 구성한 후 다음 명령을 실행하면 됩니다:
# via npm
+$ npm install qsu
+$ npm install qsu-web # (선택적) Web용 추가 유틸을 사용할 때
+
+# via yarn
+$ yarn add qsu
+$ yarn add qsu-web # (선택적) Web용 추가 유틸을 사용할 때
+
+# via pnpm
+$ pnpm install qsu
+$ pnpm install qsu-web # (선택적) Web용 추가 유틸을 사용할 때
일반적으로 각각의 함수를 아래와 같이 부분적으로 import하여 사용할 수 있습니다.
import { today, strCount } from 'qsu';
+
+function main() {
+ console.log(today()); // '20xx-xx-xx'
+ console.log(strCount('123412341234', '1')); // 3
+}
코드와 모듈의 구분을 위해 아래처럼 언더스코어(_
)기호 등을 사용하여 메소드를 사용할 수 있습니다. 특별한 경우가 아니면 부분 가져오기를 사용하는 것을 권장합니다.
import _ from 'qsu';
+
+function main() {
+ console.log(_.today()); // '20xx-xx-xx'
+}
Lightweight and extensive utility helpers
QSU is a package of utilities to energize your programming. It is available for JavaScript/Node.js and Dart/Flutter environments.
가벼우면서 광범위한 유틸리티 도우미
QSU는 프로그래밍에 활력을 주는 유틸리티를 모은 패키지입니다. JavaScript/Node.js와 Dart/Flutter 환경에서 사용할 수 있습니다.