@steveush/utils
Utility methods and classes
NOTE
Any version below 1.0.0 is considered experimental and is subject to change.
This package was created for my personal use, and so is provided as is.
Install
npm i @steveush/utils --save-dev
Usage
ESM
Import the entire package and make use of features. This is not recommended as you may lose the benefit of tree-shaking.
import * as utils from "@steveush/utils";
Instead, import the specific util.
import { isString } from "@steveush/utils";
CJS
Import the entire package and make use of features.
const utils = require( "@steveush/utils" );
Import a specific util.
const { isString } = require( "@steveush/utils" );
Number Helpers
clamp( value: number, min?: number, max?: number ): number
Clamp a number value within a given range.
Params
-
value: any
The number to clamp. If the value supplied is not a number, the min
value is returned.
-
min: number
optional
The minimum allowed value for the number. If not supplied Number.MIN_SAFE_INTEGER
is used.
-
max: number
optional
The maximum allowed value for the number. If not supplied Number.MAX_SAFE_INTEGER
is used.
Returns
number
The number clamped between the min
and max
values. If the number was smaller than the min
or larger than the max
, their respective values are instead returned.
Example
clamp( -1, 0, 2 );
clamp( 0, 0, 2 );
clamp( 1, 0, 2 );
clamp( 2, 0, 2 );
clamp( 3, 0, 2 );
isNumberNotZero( value: string | number ): boolean
Check if a value is a number and not zero.
Params
- value:
any
The value to check. If a string is supplied it is first parsed to a number using the parseFloat
method.
Returns
boolean
true
if the value is a number and not zero, otherwise false
.
Example
isNumberNotZero( 0 );
isNumberNotZero( 1 );
isNumberNotZero( "0px" );
isNumberNotZero( "1px" );
isNumberNotZero( "0.0em" );
isNumberNotZero( "0.1em" );
isNumberWithin( value: number, min: number, max: number ): boolean
Check if a value is a number within the inclusive range of min to max.
Params
-
value: any
The value to check.
-
min: number
The inclusive minimum value for the range.
-
max: number
The inclusive maximum value for the range.
Returns
boolean
true
if the value is a number within the specified range, otherwise false
.
Example
isNumberWithin( -1, 0, 2 );
isNumberWithin( 0, 0, 2 );
isNumberWithin( 1, 0, 2 );
isNumberWithin( 2, 0, 2 );
isNumberWithin( 3, 0, 2 );
Object Helpers
cleanObject( value: object | any ): object | undefined
Clean an object by removing any keys explicitly set to undefined
.
If after cleaning the object is empty, undefined
itself is returned.
Params
- value:
object | any
The object to clean. If a non-object value is supplied, undefined
will be returned.
Returns
object | undefined
An object containing all keys with defined values, otherwise undefined
.
Example
cleanObject( {} );
cleanObject( { empty: undefined } );
cleanObject( { empty: undefined, notEmpty: true } );
clone( target: any ): any
Creates a clone of the supplied target.
Note: This method will clone arrays and plain objects, all other types are set by reference.
Params
- target:
any
The target value to clone.
Returns
any
A clone of the supplied target.
combine( arr1: any[], arr2: any[], comparator?: ( ( a: any, b: any ) => boolean ) ): any[]
Combine two arrays and return a new array containing no duplicate elements.
Params
-
arr1: any[]
The first array to combine.
-
arr2: any[]
The second array to combine.
-
comparator: ( a: any, b: any ) => boolean
optional
The function used to determine element equality when removing duplicates. Defaults to a strict equality
check (a === b
).
Returns
any[]
The combined array, even if one or both parameters are not arrays an array is returned.
If both arr1
and arr2
are not arrays an empty array is returned.
If arr1
is not an array a shallow copy of arr2
is returned.
If arr2
is not an array a shallow copy of arr1
is returned.
If both arr1
and arr2
are arrays they are combined and a new array containing distinct elements is returned.
Example
combine(
[ 1, 2 ],
[ 2, 3 ]
);
combine(
[ { id: 1 }, { id: 2 } ],
[ { id: 2 }, { id: 3 } ]
);
combine(
[ { id: 1 }, { id: 2 } ],
[ { id: 2 }, { id: 3 } ],
( a, b ) => a.id === b.id
);
distinct( array: any[] ): any[]
Return the distinct elements of an array.
Params
- array:
any[]
The array to pluck elements from.
Returns
any[]
A new array containing the distinct elements.
Example
distinct( [ 1, 2, 2, 3 ] );
getProperty( target: object, path: string ): any
Get a property value from an object using a path string ("child.prop"
).
Params
Returns
any
The value found using the path, otherwise undefined
.
Example
Passing an object as the target.
const obj = {
name: "root",
child: {
name: "child"
},
children: [
{ name: "first" },
{ name: "second" }
]
};
getProperty( obj, "name" );
getProperty( obj, "child.name" );
getProperty( obj, "children[0].name" );
getProperty( obj, "children.0.name" );
getProperty( obj, "children[1].name" );
getProperty( obj, "children.1.name" );
Passing an array as the target.
const arr = [
{ name: "first" },
{ name: "second" }
];
getProperty( arr, "[0].name" );
getProperty( arr, "0.name" );
getProperty( arr, "[1].name" );
getProperty( arr, "1.name" );
hasKeys( target: object, keys?: string | string[] | Record<string, ( ( value: any ) => boolean )> ): boolean
Check if an object has keys.
Params
-
target: object
The object to check.
-
keys: string | string[] | Record<string, ( ( value: any ) => boolean )>
optional
A string key name, string array of key names, or an object containing key names to type check methods. If not supplied
and the target contains any keys, true
is returned.
Returns
boolean
true
if the target has all the keys, otherwise false
.
Example
const obj = {
name: "string",
checked: true
};
hasKeys( obj );
hasKeys( obj, "name" );
hasKeys( obj, "never" );
hasKeys( obj, [ "name", "checked" ] );
hasKeys( obj, [ "name", "checked", "never" ] );
hasKeys( obj, { name: isString, checked: isBoolean } );
hasKeys( obj, { name: isString, checked: isString } );
merge( target: object, ...source: object[] ): object
Recursively merge the properties of multiple source objects into the target.
Note: This method does not merge arrays. Any array properties of the target are replaced with shallow copies from
the sources.
Params
Returns
object
The target object is returned merged with the properties of all source objects.
Example
merge(
{ prop1: "one", prop2: false },
{ prop2: true, prop3: 2 },
{ prop1: "three", prop3: 3 }
);
If the target is not a plain object a new object is created.
merge();
merge( undefined, { prop1: "one" } );
If a source is not a plain object it is ignored.
merge( { prop1: "one" }, undefined );
merge( { prop1: "one" }, "oops" );
merge( { prop1: "one" }, undefined, { prop2: "two" } );
pluck( target: object, keys: string | string[] | ( ( value: any, key: string: iter: object ) => boolean ) ): object
Pluck key-value pairs from one object into a new object.
Params
-
target: object
The object to pluck key-value pairs from.
-
keys: string | string[] | ( ( value: any, key: string: iter: object ) => boolean )
A string key name, string array of key names, or a predicate that determines if the key-value pair should be plucked.
Returns
object
A new object containing all matching key-value pairs.
Example
const obj = {
prop1: "string1",
prop2: true,
prop3: 3,
prop4: "string2"
};
pluck( obj, "prop1" );
pluck( obj, [ "prop2", "prop3" ] );
pluck( obj, value => isString( value ) );
setProperty( target: object, path: string, value: any, create?: boolean ): void
Set a value of an object using a path string ("child.prop"
).
Params
-
target: object
The array or object to set the value on.
-
path: string
The path on the target where the value will be set.
-
value: any
The value to assign to the path.
-
create: boolean
optional
Whether to create the path on the target if it does not exist. Defaults to false
.
Example
Given the following object:
const obj = {
name: "root",
child: {
name: "child"
},
children: [
{ name: "first" },
{ name: "second" }
]
};
We can change the value of various existing properties.
setProperty( obj, "name", "update_root" );
setProperty( obj, "child.name", "update_child" );
setProperty( obj, "children[0].name", "update_children_first" );
Note: By default, if the path does not exist on the target, no property is set.
setProperty( {}, "newProp", "never" );
If you want to change this behavior and allow new properties to be created, then you must pass true
for the create
parameter.
setProperty( obj, "newProp", "created", true );
someKeys( target: object, keys?: string | string[] | Record<string, ( ( value: any ) => boolean )> ): boolean
Check if an object has some keys.
Params
-
target: object
The object to check.
-
keys: string | string[] | Record<string, ( ( value: any ) => boolean )>
optional
A string key name, string array of key names, or an object containing key names to type check methods. If not supplied
and the target contains any keys, true
is returned.
Returns
boolean
true
if the target has any of the keys, otherwise false
.
Example
const obj = {
name: "string",
checked: true
};
someKeys( obj );
someKeys( obj, "name" );
someKeys( obj, "never" );
someKeys( obj, [ "name", "never" ] );
someKeys( obj, { name: isString, checked: isString } );
someKeys( obj, { name: isBoolean, checked: isString } );
String Helpers
bisect( str: string, searchString: string, trim?: boolean ): [ string, string ]
Split a string on the first occurrence of the specified search string.
Params
-
str: string
The string to split.
-
searchString: string
The value used to split the string.
-
trim: boolean
optional
Whether the resulting parts should be trimmed. Defaults to false
.
Returns
[ string, string ]
A tuple containing the result of the split.
The first element is the string value from before the searchString
, or the original value if the searchString
was
not found.
The second element is the string value from after the searchString
, or an empty string if the searchString
was not
found.
Example
bisect( "split on first space", " " );
bisect( "split - on first - dash", "-" );
bisect( "split - on first - dash", "-", true );
capitalize( str: string ): string
Capitalize the first character of a string.
Params
- str:
string
The string to capitalize.
Returns
string
The capitalized string, otherwise an empty string if the value was not string.
Example
capitalize();
capitalize( "test" );
capitalize( "TEST" );
escapeHTML( str: string ): string
Convert the special characters &
, <
, >
, "
, and '
in a string to HTML entities.
Params
- str:
string
The string to escape.
Returns
string
The escaped string.
Example
escapeHTML( `<img src="..." title="Jack's Pub" />` );
propertyPath( path: string ): string
Convert an array notated property path to a dot notated one.
The only difference between array and dot notated paths is how array indexes are described. In array notation they are
encapsulated within square brackets, whilst in dot notation they are simply prefixed with a period like other
property names.
This method is used internally by the getProperty
and setProperty
methods to normalize the supplied path parameter.
Params
- path:
string
The path string to convert.
Returns
string
The result of the conversion.
Example
propertyPath( "[0].name" );
propertyPath( "arr[0].name" );
propertyPath( "arr[0]" );
strim( str: string, separator: string | RegExp ): string[]
Split a string into an ordered list of trimmed, non-empty, substrings.
Params
Returns
string[]
An array containing the trimmed, non-empty, substrings, split at each point where the separator occurs in the given string.
Example
strim( "key1: value1; key2: value2;", ";" );
toCamelCase( str: string, uppercase?: string[], force?: boolean ): string
Convert a string to camelCase.
Params
-
str: string
The string to convert.
-
uppercase: string[]
optional
An array of strings to convert to uppercase. Defaults to []
.
-
force: boolean
optional
Whether to allow uppercase strings to appear at the start of a string. Defaults to false
.
Returns
string
The converted camelCase string.
Example
toCamelCase( "camelCase" );
toCamelCase( "PascalCase" );
toCamelCase( "kebab-case" );
toCamelCase( "snake_case" );
toCamelCase( "with spaces" );
If you need specific parts of the string to be uppercased you can supply them as the second parameter.
toCamelCase( "camelCase", [ "case" ] );
toCamelCase( "PascalCase", [ "case" ] );
toCamelCase( "kebab-case", [ "case" ] );
toCamelCase( "snake_case", [ "case" ] );
If the string starts with one of the uppercase strings, by default it is left as lowercase.
toCamelCase( "case-at-start", [ "case" ] );
However, this can be overridden by specifying the force parameter as true
.
toCamelCase( "case-at-start", [ "case" ], true );
toKebabCase( str: string ): string
Convert a string to kebab-case.
Params
- str:
string
The string to be converted.
Returns
string
The converted kebab-case string.
Example
toKebabCase( "camelCase" );
toKebabCase( "PascalCase" );
toKebabCase( "kebab-case" );
toKebabCase( "snake_case" );
toKebabCase( "with spaces" );
toPascalCase( str: string, uppercase?: string[] ): string
Convert a string to PascalCase.
Params
Returns
string
The converted PascalCase string.
Example
toPascalCase( "camelCase" );
toPascalCase( "PascalCase" );
toPascalCase( "kebab-case" );
toPascalCase( "snake_case" );
toPascalCase( "with spaces" );
If you need specific parts of the string to be uppercased you can supply them as the second parameter.
toPascalCase( "camelCase", [ "case" ] );
toPascalCase( "PascalCase", [ "case" ] );
toPascalCase( "kebab-case", [ "case" ] );
toPascalCase( "snake_case", [ "case" ] );
toSnakeCase( str: string ): string
Convert a string to snake_case.
Params
- str:
string
The string to be converted.
Returns
string
The converted snake_case string.
Example
toSnakeCase( "camelCase" );
toSnakeCase( "PascalCase" );
toSnakeCase( "kebab-case" );
toSnakeCase( "snake_case" );
toSnakeCase( "with spaces" );
toPartsLowerCase( str: string ): string[]
Convert a string into an array of its component parts.
Used to provide a consistent base for the various string case methods to work from.
- All punctuation is stripped.
- The string is split on capitalized characters, underscores, dashes and spaces.
- The parts from the split are trimmed and lowercased.
Params
- str:
string
The string to convert.
Returns
string[]
An array containing the parts of the string.
Example
toPartsLowerCase( "camelCase" );
toPartsLowerCase( "PascalCase" );
toPartsLowerCase( "kebab-case" );
toPartsLowerCase( "snake_case" );
toPartsLowerCase( "with spaces" );
toString( value: any ): string
Convert a value to a string using the Object.prototype.toString()
method.
Params
- value:
any
The value to convert.
Returns
string
The string representation of the value.
Example
toString( "str" );
toString( true );
toString( Symbol.toStringTag );
unescapeHTML( str: string ): string
Convert the HTML entities &
, <
, >
, "
and '
in a string back to their original characters.
Params
- str:
string
The string to unescape.
Returns
string
The unescaped string.
Example
escapeHTML( `<img src="..." title="Jack's Pub" />` );
Type Checks
isArray( value: any, notEmpty?: boolean, predicate?: ( value: any, index: number, iter: any[] ) => boolean ): boolean
Check if a value is an array.
Params
-
value: any
The value to check.
-
notEmpty: boolean
optional
If true
the array must not be empty. Defaults to false
.
-
predicate: ( value: any, index: number, iter: any[] ) => boolean
optional
If supplied every entry in the array must satisfy this predicate.
Returns
boolean
true
if the value is an array and satisfies the optional checks, otherwise false
.
Example
isArray( [] );
isArray( [], true );
isArray( [ 1 ], true, value => isNumber( value ) );
isArray( [ 1, "2" ], true, value => isNumber( value ) );
isBoolean( value: any ): boolean
Check if a value is a boolean.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is a boolean, otherwise false
.
isFunction( value: any ): boolean
Check if a value is a function.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is a function, otherwise false
.
Example
function named() {
}
isFunction( named );
const arrow = () => "returns";
isFunction( arrow );
isNonNullable( value: any ): boolean
Check if a value is not null
or undefined
.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is not null
or undefined
, otherwise false
.
isNull( value: any ): boolean
Check if a value is null
.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is null
, otherwise false
.
isNumber( value: any ): boolean
Check if a value is a number.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is a number, otherwise false
.
isObject( value: any, notEmpty?: boolean, predicate?: ( ( value: any, key: string, iter: object ) => boolean ) ): boolean
Check if a value is an object.
This method returns true
for arrays, functions, objects and classes like Date
, Error
and RegExp
.
If notEmpty is true
the value must return a non-empty array from a call to Object.entries
.
If a predicate is supplied every entry in the object must satisfy it.
Params
-
value: any
The value to check.
-
notEmpty: boolean
optional
If true
the object must not be empty. Defaults to false
.
-
predicate: ( value: any, key: string, iter: object ) => boolean
optional
If supplied every entry in the object must satisfy this predicate.
Returns
boolean
true
if the value is an object and satisfies the optional checks, otherwise false
.
Example
isObject( [] );
isObject( {} );
isObject( () => 'returns' );
Checking for empty values.
isObject( [], true );
isObject( {}, true );
isObject( () => 'returns', true );
const fn = () => 'returns';
fn.prop = true;
isObject( fn, true );
Ensuring each key-value pair satisfies a condition.
isObject( [ 1, 2, 3 ], true, value => isNumber( value ) );
isObject( [ 1, 2, 3 ], true, value => isString( value ) );
isObject( { prop1: 1, prop2: 2 }, true, value => isNumber( value ) );
isObject( { prop1: 1, prop2: 2 }, true, value => isString( value ) );
isPlainObject( value: any, notEmpty?: boolean, predicate?: ( ( value: any, key: string, iter: object ) => boolean ) ): boolean
Check if a value is a plain old JavaScript object.
Params
-
value: any
The value to check.
-
notEmpty: boolean
optional
If true
the object must not be empty. Defaults to false
.
-
predicate: ( value: any, key: string, iter: object ) => boolean
optional
If supplied every entry in the object must satisfy this predicate.
Returns
boolean
true
if the value is a plain old JavaScript object and satisfies the optional checks, otherwise false
.
Example
isPlainObject( [] );
isPlainObject( {} );
isPlainObject( () => 'returns' );
Checking for empty values.
isPlainObject( {}, true );
isPlainObject( { prop: 1 }, true );
Ensuring each key-value pair satisfies a condition.
isPlainObject( { prop1: 1, prop2: 2 }, true, value => isNumber( value ) );
isPlainObject( { prop1: 1, prop2: 2 }, true, value => isString( value ) );
isRegExp( value: any ): boolean
Check if a value is a regular expression.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is a regular expression, otherwise false
.
isString( value: any, notEmpty?: boolean ): boolean
Check if a value is a string.
A string is empty if it has a length of 0 or contains only whitespace.
Params
Returns
boolean
true
if the value is a string and satisfies the optional check, otherwise false
.
isSymbol( value: any ): boolean
Check if a value is a symbol.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is a symbol, otherwise false
.
isUndefined( value: any ): boolean
Check if a value is undefined
.
Params
- value:
any
The value to check.
Returns
boolean
true
if the value is undefined
, otherwise false
.
Development
To get the project up and running for development should just require running npm install
and then npm run develop
.
For more information on the configuration check out the DEV.md readme.
Changelog
Version | Description |
---|
0.0.1 | Initial release |
0.0.2 | Relaxed the value checks for hasKeys , someKeys and pluck methods to allow any object instead of just plain objects. Added the cleanObject , clone , distinct , clamp , isNumberNotZero , isNumberWithin , capitalize and strim methods. |