steveush / utils

Utility methods and classes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@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" );

Object Helpers

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 } ]
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, otherwise undefined.

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, otherwise false.

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 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" );
// 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, otherwise false.

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

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", " " ); // => [ "split", "on first space" ]
bisect( "split - on first - dash", "-" ); // => [ "split ", " on first - dash" ]
bisect( "split - on first - dash", "-", true ); // => [ "split", "on first - dash" ]
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" />` ); // => "&lt;img src=&quot;...&quot; title=&quot;Jack&#39;s Pub&quot; /&gt;"
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"
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" ); // => "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 &amp;, &lt;, &gt;, &quot; and &#39; in a string back to their original characters.

Params

  • str: string
    The string to unescape.

Returns

  • string
    The unescaped string.

Example

escapeHTML( `&lt;img src=&quot;...&quot; title=&quot;Jack&#39;s Pub&quot; /&gt;` ); // => "<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( [] ); // => 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, 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 ); // => 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 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( [] ); // => 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
    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( [] ); // => 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, 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

  • value: any
    The value to check.

  • notEmpty: boolean optional
    If true the string must not be empty. Defaults to false.

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

About

Utility methods and classes

License:MIT License


Languages

Language:JavaScript 100.0%