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.
npm i @steveush/utils --save-dev
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";
Import the entire package and make use of features.
const utils = require( "@steveush/utils" );
Import a specific util.
const { isString } = require( "@steveush/utils" );
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, themin
value is returned. -
min:
number
optional
The minimum allowed value for the number. If not suppliedNumber.MIN_SAFE_INTEGER
is used. -
max:
number
optional
The maximum allowed value for the number. If not suppliedNumber.MAX_SAFE_INTEGER
is used.
Returns
-
number
The number clamped between themin
andmax
values. If the number was smaller than themin
or larger than themax
, their respective values are instead returned.
Example
clamp( -1, 0, 2 ); // => 0
clamp( 0, 0, 2 ); // => 0
clamp( 1, 0, 2 ); // => 1
clamp( 2, 0, 2 ); // => 2
clamp( 3, 0, 2 ); // => 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 theparseFloat
method.
Returns
-
boolean
true
if the value is a number and not zero, otherwisefalse
.
Example
isNumberNotZero( 0 ); // => false
isNumberNotZero( 1 ); // => true
isNumberNotZero( "0px" ); // => false
isNumberNotZero( "1px" ); // => true
isNumberNotZero( "0.0em" ); // => false
isNumberNotZero( "0.1em" ); // => true
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, otherwisefalse
.
Example
isNumberWithin( -1, 0, 2 ); // => false
isNumberWithin( 0, 0, 2 ); // => true
isNumberWithin( 1, 0, 2 ); // => true
isNumberWithin( 2, 0, 2 ); // => true
isNumberWithin( 3, 0, 2 ); // => false
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, otherwiseundefined
.
Example
cleanObject( {} ); // => undefined
cleanObject( { empty: undefined } ); // => undefined
cleanObject( { empty: undefined, notEmpty: true } ); // => { 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 ]
); // => [ 1, 2, 3 ]
combine(
[ { id: 1 }, { id: 2 } ],
[ { id: 2 }, { id: 3 } ]
); // => [ { id: 1 }, { id: 2 }, { id: 2 }, { id: 3 } ]
combine(
[ { id: 1 }, { id: 2 } ],
[ { id: 2 }, { id: 3 } ],
( a, b ) => a.id === b.id
); // => [ { id: 1 }, { id: 2 }, { id: 3 } ]
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 ] ); // => [ 1, 2, 3 ]
getProperty( target: object, path: string ): any
Get a property value from an object using a path string ("child.prop"
).
Params
-
target:
object
The array or object to get the value from. -
path:
string
The path on the target where the value will be fetched from.
Returns
-
any
The value found using the path, otherwiseundefined
.
Example
Passing an object as the target.
const obj = {
name: "root",
child: {
name: "child"
},
children: [
{ name: "first" },
{ name: "second" }
]
};
getProperty( obj, "name" ); // => "root"
getProperty( obj, "child.name" ); // => "child"
getProperty( obj, "children[0].name" ); // => "first"
getProperty( obj, "children.0.name" ); // => "first"
getProperty( obj, "children[1].name" ); // => "second"
getProperty( obj, "children.1.name" ); // => "second"
Passing an array as the target.
const arr = [
{ name: "first" },
{ name: "second" }
];
getProperty( arr, "[0].name" ); // => "first"
getProperty( arr, "0.name" ); // => "first"
getProperty( arr, "[1].name" ); // => "second"
getProperty( arr, "1.name" ); // => "second"
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, otherwisefalse
.
Example
const obj = {
name: "string",
checked: true
};
hasKeys( obj ); // => true
hasKeys( obj, "name" ); // => true
hasKeys( obj, "never" ); // => false
hasKeys( obj, [ "name", "checked" ] ); // => true
hasKeys( obj, [ "name", "checked", "never" ] ); // => false
hasKeys( obj, { name: isString, checked: isBoolean } ); // => true
hasKeys( obj, { name: isString, checked: isString } ); // => false
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
-
target:
object
The object to receive the properties. -
...source:
object[]
Any number of source objects to merge into the target.
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 }
); // => { prop1: "three", prop2: true, prop3: 3 }
If the target is not a plain object a new object is created.
merge(); // => {}
merge( undefined, { prop1: "one" } ); // => { prop1: "one" }
If a source is not a plain object it is ignored.
merge( { prop1: "one" }, undefined ); // => { prop1: "one" }
merge( { prop1: "one" }, "oops" ); // => { prop1: "one" }
merge( { prop1: "one" }, undefined, { prop2: "two" } ); // => { prop1: "one", 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" ); // => { prop1: "string1" }
pluck( obj, [ "prop2", "prop3" ] ); // => { prop2: true, prop3: 3 }
pluck( obj, value => isString( value ) ); // => { prop1: "string1", prop4: "string2" }
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 tofalse
.
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" );
// obj => {
// name: "update_root",
// child: {
// name: "child"
// },
// children: [
// { name: "first" },
// { name: "second" }
// ]
// }
setProperty( obj, "child.name", "update_child" );
// obj => {
// name: "root",
// child: {
// name: "update_child"
// },
// children: [
// { name: "first" },
// { name: "second" }
// ]
// }
setProperty( obj, "children[0].name", "update_children_first" );
// obj => {
// name: "root",
// child: {
// name: "child"
// },
// children: [
// { name: "update_children_first" },
// { name: "second" }
// ]
// }
Note: By default, if the path does not exist on the target, no property is set.
setProperty( {}, "newProp", "never" );
// obj => {}
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 );
// obj => { newProp: "created" }
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, otherwisefalse
.
Example
const obj = {
name: "string",
checked: true
};
someKeys( obj ); // => true
someKeys( obj, "name" ); // => true
someKeys( obj, "never" ); // => false
someKeys( obj, [ "name", "never" ] ); // => true
someKeys( obj, { name: isString, checked: isString } ); // => true
someKeys( obj, { name: isBoolean, checked: isString } ); // => false
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 tofalse
.
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", " " ); // => [ "split", "on first space" ]
bisect( "split - on first - dash", "-" ); // => [ "split ", " on first - dash" ]
bisect( "split - on first - dash", "-", true ); // => [ "split", "on first - dash" ]
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" ); // => "Test"
capitalize( "TEST" ); // => "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" />` ); // => "<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" ); // => "0.name"
propertyPath( "arr[0].name" ); // => "arr.0.name"
propertyPath( "arr[0]" ); // => "arr.0"
strim( str: string, separator: string | RegExp ): string[]
Split a string into an ordered list of trimmed, non-empty, substrings.
Params
-
str:
string
The string to split. -
separator:
string | RegExp
The pattern describing where each split should occur.
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;", ";" ); // => [ "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 tofalse
.
Returns
-
string
The converted camelCase string.
Example
toCamelCase( "camelCase" ); // => "camelCase"
toCamelCase( "PascalCase" ); // => "pascalCase"
toCamelCase( "kebab-case" ); // => "kebabCase"
toCamelCase( "snake_case" ); // => "snakeCase"
toCamelCase( "with spaces" ); // => "withSpaces"
If you need specific parts of the string to be uppercased you can supply them as the second parameter.
toCamelCase( "camelCase", [ "case" ] ); // => "camelCASE"
toCamelCase( "PascalCase", [ "case" ] ); // => "pascalCASE"
toCamelCase( "kebab-case", [ "case" ] ); // => "kebabCASE"
toCamelCase( "snake_case", [ "case" ] ); // => "snakeCASE"
If the string starts with one of the uppercase strings, by default it is left as lowercase.
toCamelCase( "case-at-start", [ "case" ] ); // => caseAtStart
However, this can be overridden by specifying the force parameter as true
.
toCamelCase( "case-at-start", [ "case" ], true ); // => CASEAtStart
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" ); // => "camel-case"
toKebabCase( "PascalCase" ); // => "pascal-case"
toKebabCase( "kebab-case" ); // => "kebab-case"
toKebabCase( "snake_case" ); // => "snake-case"
toKebabCase( "with spaces" ); // => "with-spaces"
toPascalCase( str: string, uppercase?: string[] ): string
Convert a string to PascalCase.
Params
-
str:
string
The string to convert. -
uppercase:
string[]
optional
An array of strings to convert to uppercase. Defaults to[]
.
Returns
-
string
The converted PascalCase string.
Example
toPascalCase( "camelCase" ); // => "CamelCase"
toPascalCase( "PascalCase" ); // => "PascalCase"
toPascalCase( "kebab-case" ); // => "KebabCase"
toPascalCase( "snake_case" ); // => "SnakeCase"
toPascalCase( "with spaces" ); // => "WithSpaces"
If you need specific parts of the string to be uppercased you can supply them as the second parameter.
toPascalCase( "camelCase", [ "case" ] ); // => "CamelCASE"
toPascalCase( "PascalCase", [ "case" ] ); // => "PascalCASE"
toPascalCase( "kebab-case", [ "case" ] ); // => "KebabCASE"
toPascalCase( "snake_case", [ "case" ] ); // => "SnakeCASE"
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" ); // => "camel_case"
toSnakeCase( "PascalCase" ); // => "pascal_case"
toSnakeCase( "kebab-case" ); // => "kebab_case"
toSnakeCase( "snake_case" ); // => "snake_case"
toSnakeCase( "with spaces" ); // => "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" ); // => [ "camel", "case" ]
toPartsLowerCase( "PascalCase" ); // => [ "pascal", "case" ]
toPartsLowerCase( "kebab-case" ); // => [ "kebab", "case" ]
toPartsLowerCase( "snake_case" ); // => [ "snake", "case" ]
toPartsLowerCase( "with spaces" ); // => [ "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" ); // => "[object String]"
toString( true ); // => "[object Boolean]"
toString( Symbol.toStringTag ); // => "[object Symbol]"
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" />` ); // => "<img src="..." title="Jack's Pub" />"
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
Iftrue
the array must not be empty. Defaults tofalse
. -
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, otherwisefalse
.
Example
isArray( [] ); // => true
isArray( [], true ); // => false
isArray( [ 1 ], true, value => isNumber( value ) ); // => true
isArray( [ 1, "2" ], true, value => isNumber( value ) ); // => false
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, otherwisefalse
.
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, otherwisefalse
.
Example
function named() {
}
isFunction( named ); // => true
const arrow = () => "returns";
isFunction( arrow ); // => true
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 notnull
orundefined
, otherwisefalse
.
isNull( value: any ): boolean
Check if a value is null
.
Params
-
value:
any
The value to check.
Returns
-
boolean
true
if the value isnull
, otherwisefalse
.
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, otherwisefalse
.
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
Iftrue
the object must not be empty. Defaults tofalse
. -
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, otherwisefalse
.
Example
isObject( [] ); // => true
isObject( {} ); // => true
isObject( () => 'returns' ); // => true
Checking for empty values.
isObject( [], true ); // => false
isObject( {}, true ); // => false
isObject( () => 'returns', true ); // => false
// note functions will only be not-empty if it has properties defined.
const fn = () => 'returns';
fn.prop = true;
isObject( fn, true ); // => true
Ensuring each key-value pair satisfies a condition.
isObject( [ 1, 2, 3 ], true, value => isNumber( value ) ); // => true
isObject( [ 1, 2, 3 ], true, value => isString( value ) ); // => false
isObject( { prop1: 1, prop2: 2 }, true, value => isNumber( value ) ); // => true
isObject( { prop1: 1, prop2: 2 }, true, value => isString( value ) ); // => false
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
Iftrue
the object must not be empty. Defaults tofalse
. -
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, otherwisefalse
.
Example
isPlainObject( [] ); // => false
isPlainObject( {} ); // => true
isPlainObject( () => 'returns' ); // => false
Checking for empty values.
isPlainObject( {}, true ); // => false
isPlainObject( { prop: 1 }, true ); // => true
Ensuring each key-value pair satisfies a condition.
isPlainObject( { prop1: 1, prop2: 2 }, true, value => isNumber( value ) ); // => true
isPlainObject( { prop1: 1, prop2: 2 }, true, value => isString( value ) ); // => false
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, otherwisefalse
.
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
-
value:
any
The value to check. -
notEmpty:
boolean
optional
Iftrue
the string must not be empty. Defaults tofalse
.
Returns
-
boolean
true
if the value is a string and satisfies the optional check, otherwisefalse
.
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, otherwisefalse
.
isUndefined( value: any ): boolean
Check if a value is undefined
.
Params
-
value:
any
The value to check.
Returns
-
boolean
true
if the value isundefined
, otherwisefalse
.
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.
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. |