@handy-common-utils/misc-utils
v1.15.0
Published
Miscellaneous utilities
Readme
@handy-common-utils/misc-utils
Miscellaneous utilities for JavaScript/TypeScript development.
Features
This package provides several utility categories:
- Array manipulation (distribution and sampling)
- String encoding related utilities
- Error classification helpers
- HTTP status codes and messages
- Line-based logging
- String masking for sensitive data
- JSON stringify replacers
- String substitution utilities
Installation
npm install @handy-common-utils/misc-utilsQuick Examples
Array Utilities
import { distributeRoundRobin, downSampleRandomly } from '@handy-common-utils/misc-utils';
// Distribute items evenly across groups
const items = [1, 2, 3, 4, 5, 6];
const groups = distributeRoundRobin(items, 3);
// Result: [[1,4], [2,5], [3,6]]
// Random sampling
const sample = downSampleRandomly(items, 3);
// Gets 3 random items while maintaining relative orderEncoding of Strings
import {
shortBase64UrlFromUInt32,
generateRandomString
} from '@handy-common-utils/misc-utils';
// Convert number to URL-safe base64
const urlSafeId = shortBase64UrlFromUInt32(12345);
// Generate random string (cryptographically strong)
const randomId = generateRandomString(16);
// Generate random string (no cryptographic strength)
const randomId2 = generateRandomStringQuickly(16);Error Classification
import {
couldBeNetworkingTimeoutError,
couldBeServerError,
couldBeTemporaryNetworkingError
} from '@handy-common-utils/misc-utils';
try {
await fetchData();
} catch (error) {
if (couldBeTemporaryNetworkingError(error)) {
// Retry logic
}
if (couldBeServerError(error)) {
// Log server error
}
}Line Logger
// use chalk (chalk is not a dependency of this package, you need to add chalk as a dependency separately)
import chalk from 'chalk';
import { LineLogger } from '@handy-common-utils/misc-utils';
// this.flags is an object with properties "debug" and "quiet"
this.output = LineLogger.consoleWithColour(this.flags, chalk);
this.output.warn('Configuration file not found, default configuration would be used.'); // it would be printed out in yellowString Masking
import { mask, maskAll, maskEmail, maskFullName, pathBasedReplacer } from '@handy-common-utils/misc-utils';
const masked = JSON.stringify(obj, pathBasedReplacer([
[/(^|\.)x-api-key$/i, maskAll],
[/(^|\.)customer\.name$/i, maskFullName],
[/(^|\.)customer\..*[eE]mail$/i, maskEmail],
[/(^|\.)zip$/i, (value: string) => value.slice(0, 3) + 'XX'],
[/(^|\.)cc$/i, () => undefined],
[/(^|\.)ssn$/i, mask],
]));JSON Stringify with Replacers
import { pathBasedReplacer } from '@handy-common-utils/misc-utils';
const data = {
user: {
name: 'John Smith',
email: '[email protected]',
ssn: '123-45-6789',
creditCard: '4111-1111-1111-1111'
}
};
const replacer = pathBasedReplacer([
[/\.name$/, maskFullName],
[/\.email$/, maskEmail],
[/\.ssn$/, maskAll],
[/\.creditCard$/, maskCreditCard]
]);
console.log(JSON.stringify(data, replacer, 2));String Substitution
import { substituteAll } from '@handy-common-utils/misc-utils';
// Template substitution
const template = 'Hello, {name}! Your order #{orderId} is ready.';
const values = { name: 'John', orderId: '12345' };
const result = substituteAll(template, /{([^{}]+)}/g, (_, groups) => {
return values[groups[1]] || '';
});
// Result: "Hello, John! Your order #12345 is ready."String Utilities
import {
truncate,
capitalize,
capitalise,
camelToSnake,
snakeToCamel,
pluralize,
pluralise,
applyWordCasing
} from '@handy-common-utils/misc-utils';
// Truncate a string
truncate('hello world', 8); // 'hello...'
truncate('hello world', 8, '!'); // 'hello w!'
// Capitalize/capitalise
capitalize('hELLo'); // 'Hello'
capitalise('hELLo'); // 'Hello'
// Convert camelCase to snake_case
camelToSnake('helloWorld'); // 'hello_world'
camelToSnake('JSONData'); // 'json_data'
// Convert snake_case to camelCase
snakeToCamel('hello_world'); // 'helloWorld'
snakeToCamel('hello__world'); // 'helloWorld'
// Pluralize words
pluralize('cat', 2); // 'cats'
pluralise('person', 2); // 'people'
pluralize('fish', 2); // 'fish'
// Preserve casing from template
applyWordCasing('CAT', 'dog'); // 'DOG'
applyWordCasing('Cat', 'dog'); // 'Dog'Number Utilities
import { clamp, isInRange, roundTo } from '@handy-common-utils/misc-utils';
// Clamp a number within a range
clamp(5, 0, 10); // 5
clamp(-5, 0, 10); // 0
clamp(15, 0, 10); // 10
// Check if a number is in range
isInRange(5, 0, 10); // true
isInRange(15, 0, 10); // false
// Round to decimal places
roundTo(3.14159, 2); // 3.14
roundTo(123.456, -1); // 120Masking
In software development, it's often necessary to hide sensitive information to protect user privacy or comply with regulations. Masking is a common technique used to replace part of a sensitive value with a different, non-sensitive value. For example, you might mask credit card numbers, passwords, or email addresses.
The mask(input, keepLeft = 1, keepRight = 0, minLength = 3, maskLengthOrMaskString = null, maskPattern = '*') function
can be used to mask the content of a string, replacing a part of the input string with a mask string.
It takes several optional parameters, including the number of characters to keep on the left and right sides of the string,
a minimum length for the input string to have unmask characters kept, and the mask pattern to use.
The maskEmail(input) and maskFullName(input) functions are specific variations of the mask function
that target email addresses and full names, respectively.
The maskAll(input) function masks all characters.
expect(mask(undefined)).to.be.undefined;
expect(mask(null)).to.be.null;
expect(mask('')).to.equal('');
expect(mask('abcde')).to.equal('a****');
expect(mask('abc')).to.equal('a**');
expect(mask('ab')).to.equal('**');
expect(maskEmail('[email protected]')).to.equal('j****.**@address.com');
expect(maskEmail('[email protected]')).to.equal('h**@here.com');
expect(maskEmail('[email protected]')).to.equal('**@here.com');
expect(maskEmail('[email protected]')).to.equal('**.n**.e****.a******@example.com');
expect(maskFullName('James Hu')).to.equal('J**** **');
expect(maskFullName('John Smith')).to.equal('J*** S****');
expect(maskFullName('Mike')).to.equal('M***');
expect(maskFullName('Mia')).to.equal('M**');
expect(maskFullName('Me')).to.equal('**');
expect(maskFullName('John von Neumann')).to.equal('J*** v** N******');
expect(maskFullName('Two Spaces')).to.equal('T** S*****');
expect(maskFullName('张三丰')).to.equal('张**');
expect(maskFullName('张三')).to.equal('**');Replacers for JSON.stringify(input, replacer, space)
The pathAwareReplacer(replacer, options) function allows you to build a replacer function that can be passed to JSON.stringify(input, replacer, space).
Besides the key, value, and owning object, it also exposes more information to your callback function,
such like the full property path as both a dot (.) separated string and as an array, and an array of ancestor objects.
This can be useful when you need to replace specific values in an object, but you also want to know where those values were located in the object.
pathBasedReplacer is a function that takes an array of path-based masking rules and returns a function
that can be used as the second parameter in the JSON.stringify function.
This function allows you to mask sensitive information during JSON.stringify in a very flexible way.
Each element in the rules array contains two parts: a regular expression that matches the full paths to the values you want to mask or replace, and a masking or replacing function that takes the original value as input and returns the masked or replaced value.
For example, you could use pathBasedReplacer to replace all credit card numbers in an object with masked versions of the numbers:
const maskCreditCard = (value: any) => "****-****-****-" + value.slice(-4);
const replacer = pathBasedReplacer([
[/(^|\.)billing\.cc$/i, maskCreditCard]
]);
const json = JSON.stringify({
to: '[email protected]',
cc: '[email protected]',
year: 2023,
month: 2,
orders: [
{
id: 123,
billing: {
address: '19 High Street',
cc: '1234-5678-2222-3333',
},
},
{
id: 124,
billing: {
address: '88 Main Street',
cc: '3435-8933-0009-2241',
},
},
],
}, replacer, 2);
// Combining multiple path based replaces
const replacer2 = pathBasedReplacer([
...
]);
const combinedReplacer = pathBasedReplacer([...replacer.rules, ...replacer2.rules]);substituteAll
The substituteAll(input, searchPattern, substitute) function allows you to perform substitutions on an input string
by matching a specified pattern and replacing the matches with substitution strings built by a function.
It provides flexibility in handling complex substitution scenarios through the substitute callback function.
Example Usage Scenarios:
- Templating: Replace placeholder variables in a template string with dynamic values. For example, transforming the template "Hello, {name}! How are you, {name}? I am {me}." into "Hello, John! How are you, John? I am James." by substituting
{name}with the value "John" and{me}with value "James".
const input = 'Hello, {name}! How are you, {name}? I am {me}.';
const searchPattern = /{([^{}]+)}/g;
const dict: Record<string, string> = {
name: 'John',
me: 'James',
};
const substitute: Parameters<typeof substituteAll>[2] = (_match, result) => {
const key = result[1];
return dict[key] ?? `{NOT FOUND: ${key}}`;
};
const result = substituteAll(input, searchPattern, substitute);
- Text Transformation: Modify specific segments of a string based on predefined patterns. For instance, converting dates written in a non-standard format, such as "MM/DD/YY", to a standardized format, like "YYYY-MM-DD", using a suitable regular expression pattern and substitution logic.
const input = 'Event date: 12/31/21';
const searchPattern = / ((\d{2})\/(\d{2})\/(\d{2}))/g;
const substitute = (_: string, result: any) => {
const [match, date, month, day, year] = result;
const formattedDate = `20${year}-${month}-${day}`;
return match.replace(date, formattedDate);
};
const result = substituteAll(input, searchPattern, substitute);
API
@handy-common-utils/misc-utils
Modules
| Module | Description | | ------ | ------ | | array | - | | codec | - | | errors | - | | http-status | - | | index | - | | line-logger | - | | mask | - | | merge | - | | number | - | | random | - | | string | - | | stringify-replacer | - | | substitute | - |
Array
array
Functions
| Function | Description |
| ------ | ------ |
| chunk | Splits an array into chunks of a specified size. |
| distributeRoundRobin | Distributes an array into a number of groups in a round robin fashion. This function has been tuned for performance. |
| downSampleRandomly | Down samples the input array randomly. |
| findIndexInSorted | Finds the index of an element in a sorted array using a golden ratio split (0.6180339887). |
| findInsertionIndexInSorted | Finds the index where an item should be inserted into a sorted array to maintain order, using a golden ratio split (0.6180339887) for consistent performance. |
| findInSorted | Finds an element in a sorted array using a golden ratio split (0.618) which statistically performs better than a "standard" binary search. |
| findWithinRangeInSorted | Finds all elements within a specified range in a sorted array. |
| partition | Partitions an array into multiple groups based on a classifier function. Please note that by default the returned array could have length of zero if the input array is empty, or length of 1 if the classifier always returns the same value, or length of any number depending on the classifier function. For your use case, you may want to specify initialCapacity to make sure that the returned array always contains the specified number of elements or to avoid the overhead of resizing the result array. |
| shuffle | Shuffles the elements of an array randomly using the Fisher-Yates algorithm. |
Functions
Function: chunk()
chunk<
T>(array,size):T[][]
Splits an array into chunks of a specified size.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The input array. |
| size | number | The size of each chunk. |
Returns
T[][]
An array of chunks.
Function: distributeRoundRobin()
distributeRoundRobin<
T>(array,groups):T[][]
Distributes an array into a number of groups in a round robin fashion. This function has been tuned for performance.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The input array |
| groups | number | Number of groups the elements in the input array need to be distributed into. |
Returns
T[][]
The result as an array of arrays which each represents a group
Function: downSampleRandomly()
downSampleRandomly<
T>(array,numSamples,probabilityTransformerFunction):T[]
Down samples the input array randomly.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The input array |
| numSamples | number | Number of samples to be taken from the input array. If the number of samples is greater than or equal to the length of the input array, the output array will contain all the elements in the input array. |
| probabilityTransformerFunction | (x) => number | A function that turns a random number within [0, 1) to another number within [0, 1). If not provided, the identity function F(x) = x will be used. The probability of an element being selected from the input array is determined by this function. |
Returns
T[]
A new array with the down sampled elements from the input array. The order of the elements in the output array is the same as the input array.
Function: findInSorted()
findInSorted<
T>(array,compareFn):T|undefined
Finds an element in a sorted array using a golden ratio split (0.618) which statistically performs better than a "standard" binary search.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | null | undefined | The sorted input array. If it is not sorted, the result would be incorrect. |
| compareFn | (item) => number | A function that returns: - 0 if the element is the exact match. - A negative number if the element comes before the target. - A positive number if the element comes after the target. |
Returns
T | undefined
The found element or undefined if not found or the array is null/empty.
Function: findIndexInSorted()
findIndexInSorted<
T>(array,compareFn):number|undefined
Finds the index of an element in a sorted array using a golden ratio split (0.6180339887).
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | null | undefined | The sorted input array. |
| compareFn | (item) => number | A function that returns: - 0 if the element is the exact match. - A negative number if the element comes before the target. - A positive number if the element comes after the target. |
Returns
number | undefined
The index of the found element, or undefined if not found or the array is null/empty.
Function: findInsertionIndexInSorted()
findInsertionIndexInSorted<
T,I>(array,item,compareFn):number
Finds the index where an item should be inserted into a sorted array to maintain order, using a golden ratio split (0.6180339887) for consistent performance.
Type Parameters
| Type Parameter | Default type |
| ------ | ------ |
| T | - |
| I | T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The sorted input array. |
| item | I | The item to be inserted. Please note that it does not have to be of the same type as the elements in the array. |
| compareFn | (a, b) => number | A function to compare the element in the array with the item passed in (standard comparator). Should return a negative number if the element in the array is before the item passed in, 0 if it is at the same position as the item passed in, and a positive number if the element in the array is after the item passed in. |
Returns
number
The insertion index.
Function: findWithinRangeInSorted()
findWithinRangeInSorted<
T,B>(array,lowBoundary,highBoundary,compareFn,options?):T[]
Finds all elements within a specified range in a sorted array.
Type Parameters
| Type Parameter |
| ------ |
| T |
| B |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The sorted input array. |
| lowBoundary | B | The lower boundary of the range. |
| highBoundary | B | The upper boundary of the range. |
| compareFn | (a, b) => number | A function to compare an element of type T with a boundary of type B. Should return a negative number if a < b, 0 if a === b, and a positive number if a > b. |
| options? | { highInclusive?: boolean; lowInclusive?: boolean; } | specify whether boundaries are inclusive or exclusive. By default, both are inclusive. |
| options.highInclusive? | boolean | optionally specifying whether the highBoundary is inclusive. Default is true. |
| options.lowInclusive? | boolean | optionally specifying whether the lowBoundary is inclusive. Default is true. |
Returns
T[]
An array containing all elements within the specified range.
Function: partition()
partition<
T>(array,classifier,initialCapacity?):T[][]
Partitions an array into multiple groups based on a classifier function.
Please note that by default the returned array could have length of zero if the input array is empty,
or length of 1 if the classifier always returns the same value, or length of any number depending on the classifier function.
For your use case, you may want to specify initialCapacity to make sure that the returned array always contains the
specified number of elements or to avoid the overhead of resizing the result array.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The input array. |
| classifier | (item) => number | boolean | A function that returns a boolean or a non-negative integer. - If boolean: true maps to group 0, false maps to group 1. - If number: the index of the group. Negative numbers map to group 0. |
| initialCapacity? | number | The initial capacity of the result array. If not specified, the returned array could contain any number of elements depending on the classifier function. For example, setting it to 2 could be useful for most binary classification use case. |
Returns
T[][]
An array of arrays, each representing a group.
Function: shuffle()
shuffle<
T>(array):T[]
Shuffles the elements of an array randomly using the Fisher-Yates algorithm.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| array | T[] | The input array. |
Returns
T[]
A new array with the elements shuffled.
Codec
codec
Functions
| Function | Description | | ------ | ------ | | base64FromUInt32 | Encode an unsigned 32-bit integer into BASE64 string. | | base64UrlFromUInt32 | Encode an unsigned 32-bit integer into URL/path safe BASE64 string. | | escapeForRegExp | Escape a string literal for using it inside of RegExp. (From: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) | | escapeForRegExpReplacement | Escape replacement string for using it inside of RegExp replacement parameter. (From: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) | | generateRandomString | Generate a strong (using crypto.randomFillSync(...)) random string that is URL/path safe. In the generated string, approximately every 6 characters represent randomly generated 32 bits. For example, if you need 128 bits of randomness, you just need to generate a string containing 24 characters. | | generateRandomStringQuickly | Generate a weak (using Math.random()) random string that is URL/path safe. In the generated string, approximately every 6 characters represent randomly generated 32 bits. For example, if you need 128 bits of randomness, you just need to generate a string containing 24 characters. | | shortBase64FromUInt32 | Encode an unsigned 32-bit integer into BASE64 string without trailing '='. | | shortBase64UrlFromUInt32 | Encode an unsigned 32-bit integer into URL/path safe BASE64 string without trailing '='. | | urlSafe | Make a "normal" (BASE64) string URL/path safe. |
Functions
Function: base64FromUInt32()
base64FromUInt32<
T>(ui32):string|Exclude<T,number>
Encode an unsigned 32-bit integer into BASE64 string.
Type Parameters
| Type Parameter |
| ------ |
| T extends number | null | undefined |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| ui32 | T | A 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when the value is anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32) |
Returns
string | Exclude<T, number>
BASE64 string representing the integer input, or the original input if it is null or undefined.
Function: base64UrlFromUInt32()
base64UrlFromUInt32<
T>(ui32,replacements):string|Exclude<T,number>
Encode an unsigned 32-bit integer into URL/path safe BASE64 string.
Type Parameters
| Type Parameter |
| ------ |
| T extends number | null | undefined |
Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| ui32 | T | undefined | A 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when the value is anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32) |
| replacements | string | '_-=' | A string containing replacement characters for "/", "+", and "=". If omitted, default value of '_-=' would be used. |
Returns
string | Exclude<T, number>
URL/path safe BASE64 string representing the integer input, or the original input if it is null or undefined.
Function: escapeForRegExp()
escapeForRegExp(
text):string
Escape a string literal for using it inside of RegExp. (From: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| text | string | null | undefined | the string literal to be escaped |
Returns
string
escaped string that can be used inside of RegExp, or an empty string if the input is null or undefined
Function: escapeForRegExpReplacement()
escapeForRegExpReplacement(
text):string
Escape replacement string for using it inside of RegExp replacement parameter. (From: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| text | string | null | undefined | the replacement string to be escaped, or an empty string if the input is null or undefined |
Returns
string
escaped replacement string that can be used inside of RegExp replacement parameter
Function: generateRandomString()
generateRandomString(
len):string
Generate a strong (using crypto.randomFillSync(...)) random string that is URL/path safe. In the generated string, approximately every 6 characters represent randomly generated 32 bits. For example, if you need 128 bits of randomness, you just need to generate a string containing 24 characters.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| len | number | length of the string to be generated |
Returns
string
the random string
Function: generateRandomStringQuickly()
generateRandomStringQuickly(
len):string
Generate a weak (using Math.random()) random string that is URL/path safe. In the generated string, approximately every 6 characters represent randomly generated 32 bits. For example, if you need 128 bits of randomness, you just need to generate a string containing 24 characters.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| len | number | length of the string to be generated |
Returns
string
the random string
Function: shortBase64FromUInt32()
shortBase64FromUInt32<
T>(ui32):string|Exclude<T,number>
Encode an unsigned 32-bit integer into BASE64 string without trailing '='.
Type Parameters
| Type Parameter |
| ------ |
| T extends number | null | undefined |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| ui32 | T | A 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when the value is anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32) |
Returns
string | Exclude<T, number>
BASE64 string without trailing '=' representing the integer input, or the original input if it is null or undefined.
Function: shortBase64UrlFromUInt32()
shortBase64UrlFromUInt32<
T>(ui32,replacements):string|Exclude<T,number>
Encode an unsigned 32-bit integer into URL/path safe BASE64 string without trailing '='.
Type Parameters
| Type Parameter |
| ------ |
| T extends number | null | undefined |
Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| ui32 | T | undefined | A 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when the value is anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32) |
| replacements | string | '_-' | A string containing replacement characters for "/" and "+". If omitted, default value of '_-' would be used. |
Returns
string | Exclude<T, number>
URL/path safe BASE64 string without trailing '=' representing the integer input, or the original input if it is null or undefined.
Function: urlSafe()
urlSafe<
T>(base64Input,replacements):T
Make a "normal" (BASE64) string URL/path safe.
Type Parameters
| Type Parameter |
| ------ |
| T extends string | null | undefined |
Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| base64Input | T | undefined | A (BASE64) string which could be null or undefined. |
| replacements | string | '_-=' | A string containing replacement characters for "/", "+", and "=". If omitted, default value of '_-=' would be used. |
Returns
T
URL/path safe version of the (BASE64) input string, or the original input if it is null or undefined.
Errors
errors
Functions
| Function | Description | | ------ | ------ | | couldBeNetworkingTimeoutError | Checks if the error could be a networking timeout error. | | couldBeServerError | Checks if the error could be a server error. | | couldBeTemporaryNetworkingError | Checks if the error could be a temporary networking error. |
Functions
Function: couldBeNetworkingTimeoutError()
couldBeNetworkingTimeoutError(
err):boolean
Checks if the error could be a networking timeout error.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| err | unknown | The error to check. |
Returns
boolean
True if the error is a networking timeout error, false otherwise.
Function: couldBeServerError()
couldBeServerError(
err):boolean
Checks if the error could be a server error.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| err | unknown | The error to check. |
Returns
boolean
True if the error is a server error, false otherwise.
Function: couldBeTemporaryNetworkingError()
couldBeTemporaryNetworkingError(
err):boolean
Checks if the error could be a temporary networking error.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| err | unknown | The error to check. |
Returns
boolean
True if the error is a temporary networking error, false otherwise.
Http Status
http-status
Enumerations
| Enumeration | Description | | ------ | ------ | | HttpStatusCode | Some (not all) well known HTTP status codes |
Variables
| Variable | Description | | ------ | ------ | | HttpStatusMessage | Some (not all) HTTP status messages matching their codes |
Enumerations
Enumeration: HttpStatusCode
Some (not all) well known HTTP status codes
Enumeration Members
| Enumeration Member | Value | Description |
| ------ | ------ | ------ |
| ACCEPTED202 | 202 | The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. |
| BAD_GATEWAY502 | 502 | This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. |
| BAD_REQUEST400 | 400 | This response means that server could not understand the request due to invalid syntax. |
| CONFLICT409 | 409 | This response is sent when a request conflicts with the current state of the server. |
| CREATED201 | 201 | The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request. |
| FORBIDDEN403 | 403 | The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server. |
| GATEWAY_TIMEOUT504 | 504 | This error response is given when the server is acting as a gateway and cannot get a response in time. |
| INTERNAL_SERVER_ERROR500 | 500 | The server encountered an unexpected condition that prevented it from fulfilling the request. |
| METHOD_NOT_ALLOWED405 | 405 | The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. |
| MOVED_PERMANENTLY301 | 301 | This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. |
| MOVED_TEMPORARILY302 | 302 | This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. |
| NO_CONTENT204 | 204 | There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. |
| NOT_FOUND404 | 404 | The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web. |
| NOT_IMPLEMENTED501 | 501 | The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. |
| OK200 | 200 | The request has succeeded. The meaning of a success varies depending on the HTTP method: GET: The resource has been fetched and is transmitted in the message body. HEAD: The entity headers are in the message body. POST: The resource describing the result of the action is transmitted in the message body. TRACE: The message body contains the request message as received by the server |
| PERMANENT_REDIRECT308 | 308 | This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. |
| REQUEST_TIMEOUT408 | 408 | This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. |
| SEE_OTHER303 | 303 | Server sent this response to directing client to get requested resource to another URI with an GET request. |
| SERVICE_UNAVAILABLE503 | 503 | The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. |
| TEMPORARY_REDIRECT307 | 307 | Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. |
| TOO_MANY_REQUESTS429 | 429 | The user has sent too many requests in a given amount of time ("rate limiting"). |
| UNAUTHORIZED401 | 401 | Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. |
Variables
Variable: HttpStatusMessage
constHttpStatusMessage:object
Some (not all) HTTP status messages matching their codes
Type Declaration
| Name | Type | Default value |
| ------ | ------ | ------ |
| 200 | string | 'OK' |
| 201 | string | 'Created' |
| 202 | string | 'Accepted' |
| 204 | string | 'No Content' |
| 301 | string | 'Moved Permanently' |
| 302 | string | 'Moved Temporarily' |
| 303 | string | 'See Other' |
| 307 | string | 'Temporary Redirect' |
| 308 | string | 'Permanent Redirect' |
| 400 | string | 'Bad Request' |
| 401 | string | 'Unauthorized' |
| 403 | string | 'Forbidden' |
| 404 | string | 'Not Found' |
| 405 | string | 'Method Not Allowed' |
| 408 | string | 'Request Timeout' |
| 409 | string | 'Conflict' |
| 429 | string | 'Too Many Requests' |
| 500 | string | 'Internal Server Error' |
| 501 | string | 'Not Implemented' |
| 502 | string | 'Bad Gateway' |
| 503 | string | 'Service Unavailable' |
| 504 | string | 'Gateway Timeout' |
Index
index
References
applyWordCasing
Re-exports applyWordCasing
base64FromUInt32
Re-exports base64FromUInt32
base64UrlFromUInt32
Re-exports base64UrlFromUInt32
camelToSnake
Re-exports camelToSnake
capitalise
Re-exports capitalise
capitalize
Re-exports capitalize
chunk
Re-exports chunk
clamp
Re-exports clamp
consoleLike
Re-exports consoleLike
ConsoleLineLogger
Re-exports ConsoleLineLogger
consoleWithColour
Re-exports consoleWithColour
consoleWithoutColour
Re-exports consoleWithoutColour
couldBeNetworkingTimeoutError
Re-exports couldBeNetworkingTimeoutError
couldBeServerError
Re-exports couldBeServerError
couldBeTemporaryNetworkingError
Re-exports couldBeTemporaryNetworkingError
distributeRoundRobin
Re-exports distributeRoundRobin
downSampleRandomly
Re-exports downSampleRandomly
escapeForRegExp
Re-exports escapeForRegExp
escapeForRegExpReplacement
Re-exports escapeForRegExpReplacement
escapeXml
Re-exports escapeXml
findIndexInSorted
Re-exports findIndexInSorted
findInsertionIndexInSorted
Re-exports findInsertionIndexInSorted
findInSorted
Re-exports findInSorted
findWithinRangeInSorted
Re-exports findWithinRangeInSorted
gaussianRandom
Re-exports gaussianRandom
generateRandomBoolean
Re-exports generateRandomBoolean
generateRandomInteger
Re-exports generateRandomInteger
generateRandomNumber
Re-exports generateRandomNumber
generateRandomString
Re-exports generateRandomString
generateRandomStringFromChars
Re-exports generateRandomStringFromChars
generateRandomStringQuickly
Re-exports generateRandomStringQuickly
HttpStatusCode
Re-exports HttpStatusCode
HttpStatusMessage
Re-exports HttpStatusMessage
isInRange
Re-exports isInRange
JsonStringifyReplacer
Re-exports JsonStringifyReplacer
JsonStringifyReplacerFromPathBasedRules
Re-exports JsonStringifyReplacerFromPathBasedRules
LineLogger
Re-exports LineLogger
mask
Re-exports mask
maskAll
Re-exports maskAll
maskCreditCard
Re-exports maskCreditCard
maskEmail
Re-exports maskEmail
masker
Re-exports masker
maskFullName
Re-exports maskFullName
merge
Re-exports merge
MergeOptions
Re-exports MergeOptions
NumberUtils
Re-exports NumberUtils
partition
Re-exports partition
pathAwareReplacer
Re-exports pathAwareReplacer
PathAwareReplacer
Re-exports PathAwareReplacer
pathBasedReplacer
Re-exports pathBasedReplacer
pickRandomElement
Re-exports pickRandomElement
pluralise
Re-exports pluralise
pluralize
Re-exports pluralize
rangeIntersection
Re-exports rangeIntersection
roundTo
Re-exports roundTo
seededRandom
Re-exports seededRandom
shortBase64FromUInt32
Re-exports shortBase64FromUInt32
shortBase64UrlFromUInt32
Re-exports shortBase64UrlFromUInt32
shuffle
Re-exports shuffle
snakeToCamel
Re-exports snakeToCamel
StringUtils
Re-exports StringUtils
substituteAll
Re-exports substituteAll
truncate
Re-exports truncate
unescapeXml
Re-exports unescapeXml
urlSafe
Re-exports urlSafe
weightedPickRandomElement
Re-exports weightedPickRandomElement
Line Logger
line-logger
Classes
| Class | Description | | ------ | ------ | | LineLogger | A LineLogger logs/prints one entire line of text before advancing to another line. This class is useful for encapsulating console.log/info/warn/error functions. By having an abstraction layer, your code can switching to a different output with nearly no change. |
Type Aliases
| Type Alias | Description |
| ------ | ------ |
| ConsoleLineLogger | Type of the object returned by LineLogger.console() or LineLogger.consoleWithColour(). It has the same function signatures as console.log/info/warn/error. |
Variables
| Variable | Description |
| ------ | ------ |
| consoleLike | Build an instance from 'log' (https://github.com/medikoo/log). info of the LineLogger is mapped to notice of the medikoo log. |
| consoleWithColour | Build an encapsulation of console output functions with console.log/info/warn/error and chalk/colors/cli-color. |
| consoleWithoutColour | Build an encapsulation of console output functions with console.log/info/warn/error. |
Classes
Class: LineLogger<DEBUG_FUNC, INFO_FUNC, WARN_FUNC, ERROR_FUNC>
A LineLogger logs/prints one entire line of text before advancing to another line. This class is useful for encapsulating console.log/info/warn/error functions. By having an abstraction layer, your code can switching to a different output with nearly no change.
Please note that although the name contains "Logger", this class is not intended to be used as a generic logger. It is intended for "logging for humans to read" scenario.
LineLogger.console() and LineLogger.consoleWithColour() are ready to use convenient functions.
Or you can use the constructor to build your own wrappers.
Example
// Just a wrapper of console.log/info/warn/error
const consoleLogger = LineLogger.console();
// Wrapper of console.log/info/warn/error but it mutes console.log
const lessVerboseConsoleLogger = LineLogger.console({debug: false});
// Wrapper of console.log/info/warn/error but it mutes console.log and console.info
const lessVerboseConsoleLogger = LineLogger.console({quiet: true});
// use chalk (chalk is not a dependency of this package, you need to add chalk as a dependency separately)
import chalk from 'chalk';
// this.flags is an object with properties "debug" and "quiet"
this.output = LineLogger.consoleWithColour(this.flags, chalk);
this.output.warn('Configuration file not found, default configuration would be used.'); // it would be printed out in yellowType Parameters
| Type Parameter |
| ------ |
| DEBUG_FUNC extends Function |
| INFO_FUNC extends Function |
| WARN_FUNC extends Function |
| ERROR_FUNC extends Function |
Constructors
Constructor
new LineLogger<
DEBUG_FUNC,INFO_FUNC,WARN_FUNC,ERROR_FUNC>(debugFunction,infoFunction,warnFunction,errorFunction,isDebug,isQuiet):LineLogger<DEBUG_FUNC,INFO_FUNC,WARN_FUNC,ERROR_FUNC>
Constructor
####### Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| debugFunction | DEBUG_FUNC | undefined | function for outputting debug information |
| infoFunction | INFO_FUNC | undefined | function for outputting info information |
| warnFunction | WARN_FUNC | undefined | function for outputting warn information |
| errorFunction | ERROR_FUNC | undefined | function for outputting error information |
| isDebug | boolean | false | is debug output enabled or not, it could be overriden by isQuiet |
| isQuiet | boolean | false | is quiet mode enabled or not. When quiet mode is enabled, both debug and info output would be discarded. |
####### Returns
LineLogger<DEBUG_FUNC, INFO_FUNC, WARN_FUNC, ERROR_FUNC>
Properties
| Property | Modifier | Type | Default value | Description |
| ------ | ------ | ------ | ------ | ------ |
| debug | public | DEBUG_FUNC | undefined | - |
| error | public | ERROR_FUNC | undefined | - |
| info | public | INFO_FUNC | undefined | - |
| isDebug | public | boolean | false | is debug output enabled or not, it could be overriden by isQuiet |
| isQuiet | public | boolean | false | is quiet mode enabled or not. When quiet mode is enabled, both debug and info output would be discarded. |
| warn | public | WARN_FUNC | undefined | - |
| NO_OP_FUNC | static | () => void | undefined | - |
Methods
console()
staticconsole<FLAGS>(flags,debugFlagName,quietFlagName):LineLogger<(message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void>
Build an instance with console.log/info/warn/error.
####### Type Parameters
| Type Parameter |
| ------ |
| FLAGS extends Record<string, any> |
####### Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| flags | FLAGS | ... | The flag object that contains fields for knowing whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called. |
| debugFlagName | keyof FLAGS | 'debug' | Name of the debug field in the flags object |
| quietFlagName | keyof FLAGS | 'quiet' | Name of the quiet field in the flags object |
####### Returns
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
An instance that uses console.log/info/warn/error.
consoleLike()
staticconsoleLike(log):LineLogger<(message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void>
Build an instance from 'log' (https://github.com/medikoo/log).
info of the LineLogger is mapped to notice of the medikoo log.
####### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| log | MedikooLogger | instance of the logger |
####### Returns
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
instance of LineLogger that is actually ConsoleLineLogger type
consoleWithColour()
staticconsoleWithColour<FLAGS,COLOURER>(flags,colourer,debugColourFuncName,infoColourFuncName?,warnColourFuncName?,errorColourFuncName?,debugFlagName?,quietFlagName?):LineLogger<(message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void>
Build an instance with console.log/info/warn/error and chalk/colors/cli-color. This package does not depend on chalk or colors or cli-color, you need to add them as dependencies separately.
####### Type Parameters
| Type Parameter |
| ------ |
| FLAGS extends Record<string, any> |
| COLOURER extends Record<string, any> |
####### Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| flags | FLAGS | undefined | The flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called. |
| colourer | COLOURER | undefined | Supplier of the colouring function, such as chalk or colors or cli-color |
| debugColourFuncName | keyof COLOURER | 'grey' | Name of the function within colourer that will be used to add colour to debug messages, or null if colouring is not desired. |
| infoColourFuncName? | keyof COLOURER | undefined | Name of the function within colourer that will be used to add colour to info messages, or null if colouring is not desired. |
| warnColourFuncName? | keyof COLOURER | 'yellow' | Name of the function within colourer that will be used to add colour to warn messages, or null if colouring is not desired. |
| errorColourFuncName? | keyof COLOURER | 'red' | Name of the function within colourer that will be used to add colour to error messages, or null if colouring is not desired. |
| debugFlagName? | keyof FLAGS | 'debug' | Name of the debug field in the flags object |
| quietFlagName? | keyof FLAGS | 'quiet' | Name of the quiet field in the flags object |
####### Returns
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
An instance that uses console.log/info/warn/error and also adds colour to the messages using chalk/colors/cli-color.
Type Aliases
Type Alias: ConsoleLineLogger
ConsoleLineLogger =
ReturnType<typeofconsole>
Type of the object returned by LineLogger.console() or LineLogger.consoleWithColour().
It has the same function signatures as console.log/info/warn/error.
Variables
Variable: consoleLike()
constconsoleLike: (log) =>LineLogger<(message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void> =LineLogger.consoleLike
Build an instance from 'log' (https://github.com/medikoo/log).
info of the LineLogger is mapped to notice of the medikoo log.
Build an instance from 'log' (https://github.com/medikoo/log).
info of the LineLogger is mapped to notice of the medikoo log.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| log | MedikooLogger | instance of the logger |
Returns
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
instance of LineLogger that is actually ConsoleLineLogger type
Param
instance of the logger
Returns
instance of LineLogger that is actually ConsoleLineLogger type
Variable: consoleWithColour()
constconsoleWithColour: <FLAGS,COLOURER>(flags,colourer,debugColourFuncName,infoColourFuncName?,warnColourFuncName,errorColourFuncName,debugFlagName,quietFlagName) =>LineLogger<(message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void> =LineLogger.consoleWithColour
Build an encapsulation of console output functions with console.log/info/warn/error and chalk/colors/cli-color.
Build an instance with console.log/info/warn/error and chalk/colors/cli-color. This package does not depend on chalk or colors or cli-color, you need to add them as dependencies separately.
Type Parameters
| Type Parameter |
| ------ |
| FLAGS extends Record<string, any> |
| COLOURER extends Record<string, any> |
Parameters
| Parameter | Type | Default value | Description |
| ------ | ------ | ------ | ------ |
| flags | FLAGS | undefined | The flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called. |
| colourer | COLOURER | undefined | Supplier of the colouring function, such as chalk or colors or cli-color |
| debugColourFuncName | keyof COLOURER | 'grey' | Name of the function within colourer that will be used to add colour to debug messages, or null if colouring is not desired. |
| infoColourFuncName? | keyof COLOURER | undefined | Name of the function within colourer that will be used to add colour to info messages, or null if colouring is not desired. |
| warnColourFuncName? | keyof COLOURER | 'yellow' | Name of the function within colourer that will be used to add colour to warn messages, or null if colouring is not desired. |
| errorColourFuncName? | keyof COLOURER | 'red' | Name of the function within colourer that will be used to add colour to error messages, or null if colouring is not desired. |
| debugFlagName? | keyof FLAGS | 'debug' | Name of the debug field in the flags object |
| quietFlagName? | keyof FLAGS | 'quiet' | Name of the quiet field in the flags object |
Returns
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
An instance that uses console.log/info/warn/error and also adds colour to the messages using chalk/colors/cli-color.
Param
The flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called.
Param
Supplier of the colouring function, such as chalk or colors or cli-color
Param
Name of the function within colourer that will be used to add colour to debug messages, or null if colouring is not desired.
Param
Name of the function within colourer that will be used to add colour to info messages, or null
