Miscellaneous utilities for JavaScript/TypeScript development.
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
npm install @handy-common-utils/misc-utilsimport { 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 orderimport {
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);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
}
} // 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 yellowimport { 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],
]));import { pathBasedReplacer } from '@handy-common-utils/misc-utils';
const data = {
user: {
name: 'John Smith',
email: 'john@example.com',
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));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."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'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); // 120In 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('james.hu@address.com')).to.equal('j****.**@address.com');
expect(maskEmail('her@here.com')).to.equal('h**@here.com');
expect(maskEmail('me@here.com')).to.equal('**@here.com');
expect(maskEmail('my.new.email.address@example.com')).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('**');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: 'auditor@example.com',
cc: 'auditing-trail@example.com',
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]);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.
- 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);| Module | Description |
|---|---|
| array | - |
| codec | - |
| errors | - |
| http-status | - |
| index | - |
| line-logger | - |
| mask | - |
| merge | - |
| number | - |
| string | - |
| stringify-replacer | - |
| substitute | - |
| Function | Description |
|---|---|
| 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. |
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 Parameter |
|---|
T |
| Parameter | Type | Description |
|---|---|---|
array |
T[] |
The input array |
groups |
number |
Number of groups the elements in the input array need to be distributed into. |
T[][]
The result as an array of arrays which each represents a group
downSampleRandomly<
T>(array,numSamples,probabilityTransformerFunction):T[]
Down samples the input array randomly.
| Type Parameter |
|---|
T |
| 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. |
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 | 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. |
base64FromUInt32<
T>(ui32):string|Exclude<T,number>
Encode an unsigned 32-bit integer into BASE64 string.
| Type Parameter |
|---|
T extends number | null | undefined |
| 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) |
string | Exclude<T, number>
BASE64 string representing the integer input, or the original input if it is null or undefined.
base64UrlFromUInt32<
T>(ui32,replacements):string|Exclude<T,number>
Encode an unsigned 32-bit integer into URL/path safe BASE64 string.
| Type Parameter |
|---|
T extends number | null | undefined |
| 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. |
string | Exclude<T, number>
URL/path safe BASE64 string representing the integer input, or the original input if it is null or undefined.
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)
| Parameter | Type | Description |
|---|---|---|
text |
string | null | undefined |
the string literal to be escaped |
string
escaped string that can be used inside of RegExp, or an empty string if the input is null or undefined
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)
| Parameter | Type | Description |
|---|---|---|
text |
string | null | undefined |
the replacement string to be escaped, or an empty string if the input is null or undefined |
string
escaped replacement string that can be used inside of RegExp replacement parameter
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.
| Parameter | Type | Description |
|---|---|---|
len |
number |
length of the string to be generated |
string
the random string
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.
| Parameter | Type | Description |
|---|---|---|
len |
number |
length of the string to be generated |
string
the random string
shortBase64FromUInt32<
T>(ui32):string|Exclude<T,number>
Encode an unsigned 32-bit integer into BASE64 string without trailing '='.
| Type Parameter |
|---|
T extends number | null | undefined |
| 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) |
string | Exclude<T, number>
BASE64 string without trailing '=' representing the integer input, or the original input if it is null or undefined.
shortBase64UrlFromUInt32<
T>(ui32,replacements):string|Exclude<T,number>
Encode an unsigned 32-bit integer into URL/path safe BASE64 string without trailing '='.
| Type Parameter |
|---|
T extends number | null | undefined |
| 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. |
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.
urlSafe<
T>(base64Input,replacements):T
Make a "normal" (BASE64) string URL/path safe.
| Type Parameter |
|---|
T extends string | null | undefined |
| 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. |
T
URL/path safe version of the (BASE64) input string, or the original input if it is null or undefined.
| 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. |
couldBeNetworkingTimeoutError(
err):boolean
Checks if the error could be a networking timeout error.
| Parameter | Type | Description |
|---|---|---|
err |
unknown |
The error to check. |
boolean
True if the error is a networking timeout error, false otherwise.
couldBeServerError(
err):boolean
Checks if the error could be a server error.
| Parameter | Type | Description |
|---|---|---|
err |
unknown |
The error to check. |
boolean
True if the error is a server error, false otherwise.
couldBeTemporaryNetworkingError(
err):boolean
Checks if the error could be a temporary networking error.
| Parameter | Type | Description |
|---|---|---|
err |
unknown |
The error to check. |
boolean
True if the error is a temporary networking error, false otherwise.
| Enumeration | Description |
|---|---|
| HttpStatusCode | Some (not all) well known HTTP status codes |
| Variable | Description |
|---|---|
| HttpStatusMessage | Some (not all) HTTP status messages matching their codes |
Some (not all) well known HTTP status codes
constHttpStatusMessage:object
Some (not all) HTTP status messages matching their codes
Re-exports applyWordCasing
Re-exports base64FromUInt32
Re-exports base64UrlFromUInt32
Re-exports camelToSnake
Re-exports capitalise
Re-exports capitalize
Re-exports clamp
Re-exports consoleLike
Re-exports ConsoleLineLogger
Re-exports consoleWithColour
Re-exports consoleWithoutColour
Re-exports couldBeNetworkingTimeoutError
Re-exports couldBeServerError
Re-exports couldBeTemporaryNetworkingError
Re-exports distributeRoundRobin
Re-exports downSampleRandomly
Re-exports escapeForRegExp
Re-exports escapeForRegExpReplacement
Re-exports escapeXml
Re-exports generateRandomString
Re-exports generateRandomStringQuickly
Re-exports HttpStatusCode
Re-exports HttpStatusMessage
Re-exports isInRange
Re-exports JsonStringifyReplacer
Re-exports JsonStringifyReplacerFromPathBasedRules
Re-exports LineLogger
Re-exports mask
Re-exports maskAll
Re-exports maskCreditCard
Re-exports maskEmail
Re-exports masker
Re-exports maskFullName
Re-exports merge
Re-exports MergeOptions
Re-exports NumberUtils
Re-exports pathAwareReplacer
Re-exports PathAwareReplacer
Re-exports pathBasedReplacer
Re-exports pluralise
Re-exports pluralize
Re-exports roundTo
Re-exports shortBase64FromUInt32
Re-exports shortBase64UrlFromUInt32
Re-exports snakeToCamel
Re-exports StringUtils
Re-exports substituteAll
Re-exports truncate
Re-exports unescapeXml
Re-exports urlSafe
| 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 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. |
| 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. |
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.
// 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 yellow| Type Parameter |
|---|
DEBUG_FUNC extends Function |
INFO_FUNC extends Function |
WARN_FUNC extends Function |
ERROR_FUNC extends Function |
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>
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.
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
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.
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.
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.
| Parameter | Type | Description |
|---|---|---|
log |
MedikooLogger |
instance of the logger |
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
instance of LineLogger that is actually ConsoleLineLogger type
instance of the logger
instance of LineLogger that is actually ConsoleLineLogger type
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 Parameter |
|---|
FLAGS extends Record<string, any> |
COLOURER extends Record<string, any> |
| 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 |
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.
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.
Supplier of the colouring function, such as chalk or colors or cli-color
Name of the function within colourer that will be used to add colour to debug messages, or null if colouring is not desired.
Name of the function within colourer that will be used to add colour to info messages, or null if colouring is not desired.
Name of the function within colourer that will be used to add colour to warn messages, or null if colouring is not desired.
Name of the function within colourer that will be used to add colour to error messages, or null if colouring is not desired.
Name of the debug field in the flags object
Name of the quiet field in the flags object. Quiet flag can override debug flag.
An LineLogger instance that uses console.log/info/warn/error and also adds colour to the messages using chalk/colors/cli-color.
constconsoleWithoutColour: <FLAGS>(flags,debugFlagName,quietFlagName) =>LineLogger<(message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void, (message?, ...optionalParams) =>void> =LineLogger.console
Build an encapsulation of console output functions with console.log/info/warn/error.
Build an instance with console.log/info/warn/error.
| Type Parameter |
|---|
FLAGS extends Record<string, any> |
| 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 |
LineLogger<(message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void, (message?, ...optionalParams) => void>
An instance that uses console.log/info/warn/error.
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.
Name of the debug field in the flags object
Name of the quiet field in the flags object. Quiet flag can override debug flag.
An LineLogger instance that uses console.log/info/warn/error.
| Function | Description |
|---|---|
| mask | Mask the content of a string |
| maskAll | Replace each character of the input with '*' |
| maskCreditCard | Mask credit card number string |
| maskEmail | Mask sensitive information in an email address while keeping some information for troubleshooting |
| masker | Create a mask function with pre-set parameters. |
| maskFullName | Mask sensitive information in the full name while keeping useful information for troubleshooting |
mask<
T>(input,keepLeft,keepRight,minLength,maskLengthOrMaskString,maskPattern):T
Mask the content of a string
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Default value | Description |
|---|---|---|---|
input |
T |
undefined |
The input which could also be null or undefined |
keepLeft |
number |
1 |
Number of characters on the left to be kept in the output without masking. Default value is 1. |
keepRight |
number |
0 |
Number of characters on the right to be kept in the output without masking. Default value is 0. |
minLength |
number |
3 |
Minimal length of the string for keepLeft and keepRight to be effective. If the input string is shorter than this length, the whole string would be masked. Default value is 3. |
maskLengthOrMaskString |
string | number | null | undefined |
null |
The string to be used for replacing the part in the input that needs to be masked, or the length of the mask string if a fixed length is desired, or null/undefined if the mask string should have the same length as the part to be masked. Default value is null. |
maskPattern |
string |
'*' |
The pattern to be repeated as the mask. Default value is '*'. |
T
String with masked content
maskAll<
T>(input):T
Replace each character of the input with '*'
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
input |
T |
a string or null or undefined |
T
masked string or null or undefined
maskCreditCard<
T>(input):T
Mask credit card number string
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
input |
T |
credit card number string which could also be null or undefined |
T
Something like --****-1234, or null/undefined if the input is null/undefined
maskEmail<
T>(T
Mask sensitive information in an email address while keeping some information for troubleshooting
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
email |
T |
the email address which could also be null or undefined |
T
masked email address
maskFullName<
T>(name):T
Mask sensitive information in the full name while keeping useful information for troubleshooting
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
name |
T |
the full name which could also be null or undefined |
T
masked full name
masker<
T>(keepLeft?,keepRight?,minLength?,maskLengthOrMaskString?,maskPattern?): (input) =>T
Create a mask function with pre-set parameters.
| Type Parameter | Default type |
|---|---|
T extends string | null | undefined |
string |
| Parameter | Type | Description |
|---|---|---|
keepLeft? |
number |
Number of characters on the left to be kept in the output without masking. Default value is 1. |
keepRight? |
number |
Number of characters on the right to be kept in the output without masking. Default value is 0. |
minLength? |
number |
Minimal length of the string for keepLeft and keepRight to be effective. If the input string is shorter than this length, the whole string would be masked. Default value is 3. |
maskLengthOrMaskString? |
string | number | null |
The string to be used for replacing the part in the input that needs to be masked, or the length of the mask string if a fixed length is desired, or null/undefined if the mask string should have the same length as the part to be masked. Default value is null. |
maskPattern? |
string |
The pattern to be repeated as the mask. Default value is '*'. |
A mask function that has specified parameters as pre-set
(
input):T
| Parameter | Type |
|---|---|
input |
T |
T
const maskApiKey = masker(2, 2, 10);
const maskedString = maskApiKey(myApiKey);| Interface | Description |
|---|---|
| MergeOptions | Options to customize the merge behavior. |
| Function | Description |
|---|---|
| merge | Recursively merges properties of one or more source objects into a destination object. |
merge<
T,U>(options,destination, ...sources):T&U[number]
Recursively merges properties of one or more source objects into a destination object.
| Type Parameter |
|---|
T extends object |
U extends any[] |
| Parameter | Type | Description |
|---|---|---|
options |
MergeOptions | null | undefined |
Customizes the merge behavior. |
destination |
T |
The object to merge properties into. It will be mutated unless options.immutable is true. |
...sources |
U |
The source objects. |
T & U[number]
The merged object.
Options to customize the merge behavior.
| Class | Description |
|---|---|
| NumberUtils | - |
| Variable | Description |
|---|---|
| clamp | Constrains a number within specified bounds. |
| isInRange | Checks if a number is within a specified range (inclusive). |
| roundTo | Rounds a number to a specified number of decimal places. |
new NumberUtils():
NumberUtils
####### Returns
NumberUtils
staticclamp(num,min,max):number
Constrains a number within specified bounds.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
num |
number |
The number to clamp |
min |
number |
The minimum value |
max |
number |
The maximum value |
####### Returns
number
The clamped value
staticisInRange(num,min,max):boolean
Checks if a number is within a specified range (inclusive).
####### Parameters
| Parameter | Type | Description |
|---|---|---|
num |
number |
The number to check |
min |
number |
The minimum value |
max |
number |
The maximum value |
####### Returns
boolean
True if the number is within range
staticroundTo(num,precision):number
Rounds a number to a specified number of decimal places.
####### Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
num |
number |
undefined |
The number to round |
precision |
number |
0 |
The number of decimal places (default: 0) |
####### Returns
number
Rounded number
constclamp: (num,min,max) =>number=NumberUtils.clamp
Constrains a number within specified bounds.
Constrains a number within specified bounds.
| Parameter | Type | Description |
|---|---|---|
num |
number |
The number to clamp |
min |
number |
The minimum value |
max |
number |
The maximum value |
number
The clamped value
The number to clamp
The minimum value
The maximum value
The clamped value
constisInRange: (num,min,max) =>boolean=NumberUtils.isInRange
Checks if a number is within a specified range (inclusive).
Checks if a number is within a specified range (inclusive).
| Parameter | Type | Description |
|---|---|---|
num |
number |
The number to check |
min |
number |
The minimum value |
max |
number |
The maximum value |
boolean
True if the number is within range
The number to check
The minimum value
The maximum value
True if the number is within range
constroundTo: (num,precision) =>number=NumberUtils.roundTo
Rounds a number to a specified number of decimal places.
Rounds a number to a specified number of decimal places.
| Parameter | Type | Default value | Description |
|---|---|---|---|
num |
number |
undefined |
The number to round |
precision |
number |
0 |
The number of decimal places (default: 0) |
number
Rounded number
The number to round
The number of decimal places (default: 0)
Rounded number
| Class | Description |
|---|---|
| StringUtils | - |
| Variable | Description |
|---|---|
| applyWordCasing | Preserve basic casing from a template single word and apply it to another word. |
| camelToSnake | Converts a camelCase string to snake_case. |
| capitalise | Capitalises the first letter of a string, making the rest lowercase. |
| capitalize | Capitalizes the first letter of a string, making the rest lowercase. |
| escapeXml | Escapes special XML entities/characters in a string. Replaces &, <, >, ", and ' with their corresponding XML entities. Designed for performance using a single pass and lookup table. |
| pluralise | Returns the plural form of a single English word based on the supplied count (alias). |
| pluralize | Returns the plural form of a single English word based on the supplied count. |
| snakeToCamel | Converts a snake_case string to camelCase. |
| truncate | Truncates a string to a specified length, optionally adding a suffix. |
| unescapeXml | Unescapes XML entities/characters in a string. Converts &, <, >, ", ' back to their original characters. |
new StringUtils():
StringUtils
####### Returns
StringUtils
staticapplyWordCasing(casingTemplate,word):string
Preserve basic casing from a template single word and apply it to another word.
Rules:
- If
casingTemplateis all upper-case, returnwordin all upper-case. - If
casingTemplateis Title Case (first letter uppercase, rest lowercase), returnwordin Title Case. - Otherwise return
wordas-is.
This helper focuses on single-word tokens only and intentionally does not handle complex multi-word or mixed-case patterns. Use for word-level casing preservation (for example, to preserve input casing when returning a pluralized form).
####### Parameters
| Parameter | Type | Description |
|---|---|---|
casingTemplate |
string |
A word whose casing should be copied (e.g. 'Cat' or 'CAT') |
word |
string |
The word to apply casing to (usually a transformed/lowercased form) |
####### Returns
string
The word adjusted to match the template's basic casing
staticcamelToSnake(str):string
Converts a camelCase string to snake_case.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
str |
string |
The camelCase string to convert |
####### Returns
string
snake_case string
staticcapitalise(str):string
Capitalises the first letter of a string, making the rest lowercase.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
str |
string |
The string to capitalise |
####### Returns
string
Capitalised string
staticcapitalize(str):string
Capitalizes the first letter of a string, making the rest lowercase.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
str |
string |
The string to capitalize |
####### Returns
string
Capitalized string
staticescapeXml<T>(str):T
Escapes special XML entities/characters in a string. Replaces &, <, >, ", and ' with their corresponding XML entities. Designed for performance using a single pass and lookup table.
####### Type Parameters
| Type Parameter |
|---|
T extends string | null | undefined |
####### Parameters
| Parameter | Type | Description |
|---|---|---|
str |
T |
The string to escape for XML |
####### Returns
T
The escaped XML string
staticpluralise(word,count):string
Returns the plural form of a single English word based on the supplied count.
Capabilities:
- Preserves basic input casing (using
applyWordCasing) so e.g. "Cat" -> "Cats", "CAT" -> "CATS". - Handles common irregular plurals (person->people, child->children, mouse->mice, etc.).
- Treats a number of nouns as uncountable (sheep, fish, species, series, news, etc.).
- Applies common rules: f/fe -> ves (knife->knives), consonant+y -> ies (baby->babies), words ending with s/x/z/ch/sh -> add 'es'.
- For words ending with 'o' there is a small exceptions list that will add 'es' (hero, potato, tomato, echo, torpedo); otherwise 's' is added.
Limitations and notes:
- This is a pragmatic, rule-based implementation covering the most common English cases, not a complete linguistic solution. It does not support locales or full irregular/exception lists (many English words have irregular forms not included here).
- The function expects a single word token. It does not pluralize multi-word phrases or attempt to inflect verbs. Use a dedicated library (for example, the 'pluralize' npm package) if you need comprehensive, production-grade pluralization.
- Casing preservation is basic (all-caps and Title Case); mixed/mid-word casing (camelCase, acronyms inside words) is not fully reconstructed.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
word |
string |
The single English word to pluralize (may be mixed case) |
count |
number |
The numeric count; if equal to 1 the original word is returned |
####### Returns
string
The pluralized word with basic casing preserved
staticpluralize(word,count):string
Returns the plural form of a single English word based on the supplied count.
Capabilities:
- Preserves basic input casing (using
applyWordCasing) so e.g. "Cat" -> "Cats", "CAT" -> "CATS". - Handles common irregular plurals (person->people, child->children, mouse->mice, etc.).
- Treats a number of nouns as uncountable (sheep, fish, species, series, news, etc.).
- Applies common rules: f/fe -> ves (knife->knives), consonant+y -> ies (baby->babies), words ending with s/x/z/ch/sh -> add 'es'.
- For words ending with 'o' there is a small exceptions list that will add 'es' (hero, potato, tomato, echo, torpedo); otherwise 's' is added.
Limitations and notes:
- This is a pragmatic, rule-based implementation covering the most common English cases, not a complete linguistic solution. It does not support locales or full irregular/exception lists (many English words have irregular forms not included here).
- The function expects a single word token. It does not pluralize multi-word phrases or attempt to inflect verbs. Use a dedicated library (for example, the 'pluralize' npm package) if you need comprehensive, production-grade pluralization.
- Casing preservation is basic (all-caps and Title Case); mixed/mid-word casing (camelCase, acronyms inside words) is not fully reconstructed.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
word |
string |
The single English word to pluralize (may be mixed case) |
count |
number |
The numeric count; if equal to 1 the original word is returned |
####### Returns
string
The pluralized word with basic casing preserved
staticsnakeToCamel(str):string
Converts a snake_case string to camelCase.
####### Parameters
| Parameter | Type | Description |
|---|---|---|
str |
string |
The snake_case string to convert |
####### Returns
string
camelCase string
statictruncate(str,length,suffix):string
Truncates a string to a specified length, optionally adding a suffix.
####### Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
str |
string |
undefined |
The string to truncate |
length |
number |
undefined |
Maximum length of the resulting string (including suffix if provided) |
suffix |
string |
'...' |
Optional suffix to add to truncated string (default: '...') |
####### Returns
string
Truncated string
staticunescapeXml<T>(str):T
Unescapes XML entities/characters in a string. Converts &, <, >, ", ' back to their original characters.
####### Type Parameters
| Type Parameter |
|---|
T extends string | null | undefined |
####### Parameters
| Parameter | Type | Description |
|---|---|---|
str |
T |
The string to unescape from XML |
####### Returns
T
The unescaped string
constapplyWordCasing: (casingTemplate,word) =>string=StringUtils.applyWordCasing
Preserve basic casing from a template single word and apply it to another word.
Rules:
- If
casingTemplateis all upper-case, returnwordin all upper-case. - If
casingTemplateis Title Case (first letter uppercase, rest lowercase), returnwordin Title Case. - Otherwise return
wordas-is.
This helper focuses on single-word tokens only and intentionally does not handle complex multi-word or mixed-case patterns. Use for word-level casing preservation (for example, to preserve input casing when returning a pluralized form).
Preserve basic casing from a template single word and apply it to another word.
Rules:
- If
casingTemplateis all upper-case, returnwordin all upper-case. - If
casingTemplateis Title Case (first letter uppercase, rest lowercase), returnwordin Title Case. - Otherwise return
wordas-is.
This helper focuses on single-word tokens only and intentionally does not handle complex multi-word or mixed-case patterns. Use for word-level casing preservation (for example, to preserve input casing when returning a pluralized form).
| Parameter | Type | Description |
|---|---|---|
casingTemplate |
string |
A word whose casing should be copied (e.g. 'Cat' or 'CAT') |
word |
string |
The word to apply casing to (usually a transformed/lowercased form) |
string
The word adjusted to match the template's basic casing
A word whose casing should be copied (e.g. 'Cat' or 'CAT')
The word to apply casing to (usually a transformed/lowercased form)
The word adjusted to match the template's basic casing
constcamelToSnake: (str) =>string=StringUtils.camelToSnake
Converts a camelCase string to snake_case.
Converts a camelCase string to snake_case.
| Parameter | Type | Description |
|---|---|---|
str |
string |
The camelCase string to convert |
string
snake_case string
The camelCase string to convert
snake_case string
constcapitalise: (str) =>string=StringUtils.capitalise
Capitalises the first letter of a string, making the rest lowercase.
Capitalises the first letter of a string, making the rest lowercase.
| Parameter | Type | Description |
|---|---|---|
str |
string |
The string to capitalise |
string
Capitalised string
The string to capitalise
Capitalised string
constcapitalize: (str) =>string=StringUtils.capitalize
Capitalizes the first letter of a string, making the rest lowercase.
Capitalizes the first letter of a string, making the rest lowercase.
| Parameter | Type | Description |
|---|---|---|
str |
string |
The string to capitalize |
string
Capitalized string
The string to capitalize
Capitalized string
constescapeXml: <T>(str) =>T=StringUtils.escapeXml
Escapes special XML entities/characters in a string. Replaces &, <, >, ", and ' with their corresponding XML entities. Designed for performance using a single pass and lookup table.
Escapes special XML entities/characters in a string. Replaces &, <, >, ", and ' with their corresponding XML entities. Designed for performance using a single pass and lookup table.
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
str |
T |
The string to escape for XML |
T
The escaped XML string
The string to escape for XML
The escaped XML string
constpluralise: (word,count) =>string=StringUtils.pluralise
Returns the plural form of a single English word based on the supplied count (alias).
See pluralize for capabilities and limitations.
Returns the plural form of a single English word based on the supplied count.
Capabilities:
- Preserves basic input casing (using
applyWordCasing) so e.g. "Cat" -> "Cats", "CAT" -> "CATS". - Handles common irregular plurals (person->people, child->children, mouse->mice, etc.).
- Treats a number of nouns as uncountable (sheep, fish, species, series, news, etc.).
- Applies common rules: f/fe -> ves (knife->knives), consonant+y -> ies (baby->babies), words ending with s/x/z/ch/sh -> add 'es'.
- For words ending with 'o' there is a small exceptions list that will add 'es' (hero, potato, tomato, echo, torpedo); otherwise 's' is added.
Limitations and notes:
- This is a pragmatic, rule-based implementation covering the most common English cases, not a complete linguistic solution. It does not support locales or full irregular/exception lists (many English words have irregular forms not included here).
- The function expects a single word token. It does not pluralize multi-word phrases or attempt to inflect verbs. Use a dedicated library (for example, the 'pluralize' npm package) if you need comprehensive, production-grade pluralization.
- Casing preservation is basic (all-caps and Title Case); mixed/mid-word casing (camelCase, acronyms inside words) is not fully reconstructed.
| Parameter | Type | Description |
|---|---|---|
word |
string |
The single English word to pluralize (may be mixed case) |
count |
number |
The numeric count; if equal to 1 the original word is returned |
string
The pluralized word with basic casing preserved
The single English word to pluralize (may be mixed case)
The numeric count; if equal to 1 the original word is returned
The pluralized word with basic casing preserved
constpluralize: (word,count) =>string=StringUtils.pluralize
Returns the plural form of a single English word based on the supplied count.
Capabilities:
- Preserves basic input casing (using
applyWordCasing) so e.g. "Cat" -> "Cats", "CAT" -> "CATS". - Handles common irregular plurals (person->people, child->children, mouse->mice, etc.).
- Treats a number of nouns as uncountable (sheep, fish, species, series, news, etc.).
- Applies common rules: f/fe -> ves (knife->knives), consonant+y -> ies (baby->babies), words ending with s/x/z/ch/sh -> add 'es'.
- For words ending with 'o' there is a small exceptions list that will add 'es' (hero, potato, tomato, echo, torpedo); otherwise 's' is added.
Limitations and notes:
- This is a pragmatic, rule-based implementation covering the most common English cases, not a complete linguistic solution. It does not support locales or full irregular/exception lists (many English words have irregular forms not included here).
- The function expects a single word token. It does not pluralize multi-word phrases or attempt to inflect verbs. Use a dedicated library (for example, the 'pluralize' npm package) if you need comprehensive, production-grade pluralization.
- Casing preservation is basic (all-caps and Title Case); mixed/mid-word casing (camelCase, acronyms inside words) is not fully reconstructed.
Returns the plural form of a single English word based on the supplied count.
Capabilities:
- Preserves basic input casing (using
applyWordCasing) so e.g. "Cat" -> "Cats", "CAT" -> "CATS". - Handles common irregular plurals (person->people, child->children, mouse->mice, etc.).
- Treats a number of nouns as uncountable (sheep, fish, species, series, news, etc.).
- Applies common rules: f/fe -> ves (knife->knives), consonant+y -> ies (baby->babies), words ending with s/x/z/ch/sh -> add 'es'.
- For words ending with 'o' there is a small exceptions list that will add 'es' (hero, potato, tomato, echo, torpedo); otherwise 's' is added.
Limitations and notes:
- This is a pragmatic, rule-based implementation covering the most common English cases, not a complete linguistic solution. It does not support locales or full irregular/exception lists (many English words have irregular forms not included here).
- The function expects a single word token. It does not pluralize multi-word phrases or attempt to inflect verbs. Use a dedicated library (for example, the 'pluralize' npm package) if you need comprehensive, production-grade pluralization.
- Casing preservation is basic (all-caps and Title Case); mixed/mid-word casing (camelCase, acronyms inside words) is not fully reconstructed.
| Parameter | Type | Description |
|---|---|---|
word |
string |
The single English word to pluralize (may be mixed case) |
count |
number |
The numeric count; if equal to 1 the original word is returned |
string
The pluralized word with basic casing preserved
The single English word to pluralize (may be mixed case)
The numeric count; if equal to 1 the original word is returned
The pluralized word with basic casing preserved
constsnakeToCamel: (str) =>string=StringUtils.snakeToCamel
Converts a snake_case string to camelCase.
Converts a snake_case string to camelCase.
| Parameter | Type | Description |
|---|---|---|
str |
string |
The snake_case string to convert |
string
camelCase string
The snake_case string to convert
camelCase string
consttruncate: (str,length,suffix) =>string=StringUtils.truncate
Truncates a string to a specified length, optionally adding a suffix.
Truncates a string to a specified length, optionally adding a suffix.
| Parameter | Type | Default value | Description |
|---|---|---|---|
str |
string |
undefined |
The string to truncate |
length |
number |
undefined |
Maximum length of the resulting string (including suffix if provided) |
suffix |
string |
'...' |
Optional suffix to add to truncated string (default: '...') |
string
Truncated string
The string to truncate
Maximum length of the resulting string (including suffix if provided)
Optional suffix to add to truncated string (default: '...')
Truncated string
constunescapeXml: <T>(str) =>T=StringUtils.unescapeXml
Unescapes XML entities/characters in a string. Converts &, <, >, ", ' back to their original characters.
Unescapes XML entities/characters in a string. Converts &, <, >, ", ' back to their original characters.
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
str |
T |
The string to unescape from XML |
T
The unescaped string
The string to unescape from XML
The unescaped string
| Type Alias | Description |
|---|---|
| JsonStringifyReplacer | The original replacer expected by JSON.stringify(...) |
| JsonStringifyReplacerFromPathBasedRules | A JsonStringifyReplacer that was created from path based rules. Those rules are stored in the rules property in case of need. |
| PathAwareReplacer | The replacer that can potentially utilise the full path of the property in the object. |
| Function | Description |
|---|---|
| pathAwareReplacer | Build a replacer function that can be passed to JSON.stringify(...). |
| pathBasedReplacer | Create a replacer function for JSON.stringify(...) from an array of path based rules. This function is useful for creating masking replacers which can apply masking based on the path of the property. |
pathAwareReplacer(
replacer,options?):JsonStringifyReplacer
Build a replacer function that can be passed to JSON.stringify(...).
| Parameter | Type | Description |
|---|---|---|
replacer |
PathAwareReplacer |
The actual replacer function which could utilise additional information. |
options? |
{ ancestors?: boolean; pathArray?: boolean; } |
Options to control whether the pathArray and ancestors parameters would have values populated. By default all information available would be populated. There is no need to specify options unless you are extremely concerned about performance, for example if you need to frequently stringify 500MB objects. |
options.ancestors? |
boolean |
When false, ancestors would be an empty array. |
options.pathArray? |
boolean |
When false, pathArray would be an empty array. This would remove the need to construct a pathArray from the path string. |
The replacer function that can be passed to JSON.stringify(...).
pathBasedReplacer(
rules):JsonStringifyReplacerFromPathBasedRules
Create a replacer function for JSON.stringify(...) from an array of path based rules. This function is useful for creating masking replacers which can apply masking based on the path of the property.
| Parameter | Type | Description |
|---|---|---|
rules |
[RegExp, (input) => any][] |
Array of rules: if the regular expression tests true with the property path, the replacer function will be applied on the value |
JsonStringifyReplacerFromPathBasedRules
The replacer function built from those path based rules. It also has a rules property storing all the path based rules provided as inputs.
import { mask, maskAll, maskEmail, maskFullName, pathBasedReplacer } from '@handy-common-utils/misc-utils';
console.log(JSON.stringify(obj, pathBasedReplacer([
[/.*\.x-api-key$/, maskAll],
[/.*customer\.name$/, maskFullName],
[/.*customer\..*[eE]mail$/, maskEmail],
[/.*\.zip$/, (value: string) => value.slice(0, 3) + 'XX'],
[/.*\.cc$/, () => undefined],
[/.*\.ssn$/, mask],
])));JsonStringifyReplacer = (
this,key,value) =>any
The original replacer expected by JSON.stringify(...)
| Parameter | Type |
|---|---|
this |
any |
key |
string |
value |
any |
any
JsonStringifyReplacerFromPathBasedRules =
JsonStringifyReplacer&object
A JsonStringifyReplacer that was created from path based rules.
Those rules are stored in the rules property in case of need.
| Name | Type |
|---|---|
rules |
[RegExp, (input) => any][] |
PathAwareReplacer = (
key,value,path,parent,pathArray,ancestors) =>any
The replacer that can potentially utilise the full path of the property in the object.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Name of the property, or the index in the parent array. |
value |
any |
Value of the property or the object in the parent array. |
path |
string |
The full path of the property in the object, such like "access.visitor.location" or "request.x-forwarded-for.0". Please note that the special characters (including ".") in property names are not escaped, for example, "order.billing address.first line". |
parent |
Parent |
The object that the property or the element belongs to. It could be { '': <the original object> } when this replacer function is called the first time. |
pathArray |
string[] |
The full path as an array. It is more useful than path in case special characters exist in property names. When this replacer function is called the first time, pathArray array would have a zero length. |
ancestors |
Parent[] |
All the ancestor objects/arrays of the property. When this replacer function is called the first time, ancestors array would have a zero length. |
any
| Function | Description |
|---|---|
| substituteAll | Substitute all occurrences of a pattern in a string. |
substituteAll<
T>(input,searchPattern,substitute):T
Substitute all occurrences of a pattern in a string.
| Type Parameter |
|---|
T extends string | null | undefined |
| Parameter | Type | Description |
|---|---|---|
input |
T |
The input string on which the substitutions will be performed. |
searchPattern |
RegExp |
The regular expression pattern used to search for segments that should be substituted. It must have the g flag set. If the beginning part of the input should be skipped, set the lastIndex of the searchPattern before calling this function. After all the substitution are done, the lastIndex of the searchPattern will be reset to zero. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex |
substitute |
(match, matchResult) => string | null |
TThe function that builds the substitution string. It is called with the matched substring and the result of RegExp.exec(). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#examples. The function can return null to indicate that no further substitution is desired. In such case, the lastIndex of the searchPattern will not be reset to zero. |
T
The resulting string after performing all substitutions.