Skip to main content

core-helpers

package @remirror/core-helpers

class RemirrorError

This marks the error as a remirror specific error, with enhanced stack tracing capabilities.

Signature:

export declare class RemirrorError extends BaseError 

Extends: BaseError

Remarks:

Use this when creating your own extensions and notifying the user that something has gone wrong.

(Some inherited members may not be shown because they are not represented in the documentation.)

property errorCode

The error code used to create this error message.

Signature:

errorCode: ErrorConstant;

property url

The link to read more about the error online.

Signature:

url: string;

method create

A shorthand way of creating an error message.

Signature:

static create(options?: RemirrorErrorOptions): RemirrorError;

Parameters:

ParameterTypeDescription
optionsRemirrorErrorOptions(Optional)

Returns:

RemirrorError

function assert()

Assert the value is truthy. Good for defensive programming, especially after enabling noUncheckedIndexedAccess in the tsconfig compilerOptions.

Signature:

export declare function assert(testValue: unknown, message?: string): asserts testValue;

Parameters:

ParameterTypeDescription
testValueunknown
messagestring(Optional)

Returns:

asserts testValue

function assertGet()

Get the key from a given value. Throw an error if the referenced property is undefined.

Signature:

export declare function assertGet<Value extends object, Key extends keyof Value>(value: Value, key: Key, message?: string): Value[Key];

Parameters:

ParameterTypeDescription
valueValue
keyKey
messagestring(Optional)

Returns:

Value[Key]

function callIfDefined()

Calls a function if defined and provides compile time type checking for the passed in parameters.

Signature:

export declare function callIfDefined<Method extends AnyFunction>(fn: Nullable<Method>, ...args: Parameters<Method>): void;

Parameters:

ParameterTypeDescription
fnNullable<Method>the function to call if it exists
argsParameters<Method>the rest of the parameters with types

Returns:

void

function capitalize()

Capitalizes a string value.

Signature:

export declare function capitalize(string: string): string;

Parameters:

ParameterTypeDescription
stringstring

Returns:

string

function Cast()

Type cast an argument. If no type is provided it will default to any.

Signature:

export declare function Cast<Type = any>(value: unknown): Type;

Parameters:

ParameterTypeDescription
valueunknown

Returns:

Type

function clamp()

Clamps the value to the provided range.

Signature:

export declare function clamp({ min, max, value }: ClampProps): number;

Parameters:

ParameterTypeDescription
{ min, max, value }ClampProps

Returns:

number

function cleanupOS()

A utility function to clean up the Operating System name.

Signature:

export declare function cleanupOS(os: string, pattern?: string, label?: string): string;

Parameters:

ParameterTypeDescription
osstringthe OS name to clean up.
patternstring(Optional) a RegExp pattern matching the OS name.
labelstring(Optional) a label for the OS.

Returns:

string

a cleaned up Operating System name

function clone()

Clones a plain object using object spread notation

Signature:

export declare function clone<Type extends object>(value: Type): Type;

Parameters:

ParameterTypeDescription
valueTypethe value to check

Returns:

Type

function cx()

Signature:

export declare function cx(...classes: ClassName[]): string;

Parameters:

ParameterTypeDescription
classesClassName[]

Returns:

string

function deepMerge()

A deep merge which only merges plain objects and Arrays. It clones the object before the merge so will not mutate any of the passed in values.

To completely remove a key you can use the Merge helper class which replaces it's key with a completely new object

Signature:

export declare function deepMerge<Type = any>(...objects: Array<object | unknown[]>): Type;

Parameters:

ParameterTypeDescription
objectsArray<object | unknown[]>

Returns:

Type

function entries()

A typesafe implementation of Object.entries()

Taken from https://github.com/biggyspender/ts-entries/blob/master/src/ts-entries.ts

Signature:

export declare function entries<Type extends object, Key extends Extract<keyof Type, string>, Value extends Type[Key], Entry extends [Key, Value]>(value: Type): Entry[];

Parameters:

ParameterTypeDescription
valueType

Returns:

Entry[]

function findMatches()

Finds all the regex matches for a string

Signature:

export declare function findMatches(text: string, regexp: RegExp, runWhile?: (match: RegExpExecArray | null) => boolean): RegExpExecArray[];

Parameters:

ParameterTypeDescription
textstringthe text to check against
regexpRegExpthe regex (which should include a 'g' flag)
runWhile(match: RegExpExecArray | null) => boolean(Optional)

Returns:

RegExpExecArray[]

function flattenArray()

Flattens an array.

Signature:

export declare function flattenArray<Type>(array: any[]): Type[];

Parameters:

ParameterTypeDescription
arrayany[]

Returns:

Type[]

function format()

Trim and conditionally capitalize string values.

Signature:

export declare function format(value: string): string;

Parameters:

ParameterTypeDescription
valuestring

Returns:

string

function freeze()

A freeze method for objects that only runs in development. Helps prevent code that shouldn't be mutated from being mutated during development.

Signature:

export declare function freeze<Target extends object>(target: Target, options?: FreezeOptions): Readonly<Target>;

Parameters:

ParameterTypeDescription
targetTarget
optionsFreezeOptions(Optional)

Returns:

Readonly<Target>

Remarks:

This function passes the value back unchanged when in a production environment. It's purpose is to help prevent bad practice while developing by avoiding mutation of values that shouldn't be mutated.

function get()

Get a property from an object or array by a string path or an array path.

Signature:

export declare function get<Return>(root: Shape, path: string | string[], defaultValue?: unknown): Return;

Parameters:

ParameterTypeDescription
rootShape
pathstring | string[]path to property
defaultValueunknown(Optional)

Returns:

Return

function getLazyArray()

Helper for getting an array from a function or array.

Signature:

export declare function getLazyArray<Type>(value: Type[] | (() => Type[])): Type[];

Parameters:

ParameterTypeDescription
valueType[] | (() => Type[])

Returns:

Type[]

function hasOwnProperty()

Safe implementation of hasOwnProperty with typechecking.

Signature:

export declare function hasOwnProperty<Obj extends object, Property extends string | number | symbol>(object_: Obj, key: Property): object_ is Property extends keyof Obj ? Obj : Obj & {
Key: unknown;
};

Parameters:

ParameterTypeDescription
object_Obj
keyPropertythe property to check

Returns:

object_ is Property extends keyof Obj ? Obj : Obj & { Key: unknown; }

Remarks:

See https://eslint.org/docs/rules/no-prototype-builtins

function includes()

A more lenient typed version of Array.prototype.includes which allow less specific types to be checked.

Signature:

export declare function includes<Type>(array: Type[] | readonly Type[], item: unknown, fromIndex?: number): item is Type;

Parameters:

ParameterTypeDescription
arrayType[] | readonly Type[]
itemunknown
fromIndexnumber(Optional)

Returns:

item is Type

function invariant()

Throw an error if the condition fails. Strip out error messages for production. Adapted from tiny-invariant.

Signature:

export declare function invariant(condition: unknown, options: RemirrorErrorOptions): asserts condition;

Parameters:

ParameterTypeDescription
conditionunknown
optionsRemirrorErrorOptions

Returns:

asserts condition

function isAndroidOS()

A utility function to check whether the current browser is running on the android platform.

Signature:

export declare function isAndroidOS(): boolean;

Returns:

boolean

function isBoolean()

Predicate check that value is boolean

Signature:

export declare function isBoolean(value: unknown): value is boolean;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is boolean

function isClass()

Warning: This API is now obsolete.

Due to the current build process stripping out classes

Predicate check that value is a class

Signature:

export declare function isClass(value: unknown): value is AnyConstructor;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is AnyConstructor

function isDirectInstanceOf()

Check if an instance is the direct instance of the provided class.

Signature:

export declare function isDirectInstanceOf<Type>(instance: unknown, Constructor: AnyConstructor<Type>): instance is Type;

Parameters:

ParameterTypeDescription
instanceunknown
ConstructorAnyConstructor<Type>

Returns:

instance is Type

function isEmptyArray()

Predicate check that value is an empty array

Signature:

export declare function isEmptyArray(value: unknown): value is never[];

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is never[]

function isEmptyObject()

Predicate check that value is an empty object

Signature:

export declare function isEmptyObject(value: unknown): boolean;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

boolean

function isInstanceOf()

A shorthand method for creating instance of checks.

Signature:

export declare function isInstanceOf<Constructor extends AnyConstructor>(Constructor: Constructor): (value: unknown) => value is InstanceType<Constructor>;

Parameters:

ParameterTypeDescription
ConstructorConstructor

Returns:

(value: unknown) => value is InstanceType<Constructor>

function isInteger()

Helper function for Number.isInteger check allowing non numbers to be tested

Signature:

export declare function isInteger(value: unknown): value is number;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is number

function isJSONPrimitive()

Predicate check for whether passed in value is a JSON primitive value

Signature:

export declare function isJSONPrimitive(value: unknown): value is JsonPrimitive;

Parameters:

ParameterTypeDescription
valueunknown

Returns:

value is JsonPrimitive

function isMap()

Predicate check that value is a Map

Signature:

export declare function isMap(value: unknown): value is Map<unknown, unknown>;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is Map<unknown, unknown>

function isNativePromise()

Predicate check that value is a native promise

Signature:

export declare function isNativePromise(value: unknown): value is Promise<unknown>;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is Promise<unknown>

function isNonEmptyArray()

Predicate check that value is a non-empty.

Signature:

export declare function isNonEmptyArray<Item>(value: Item[]): value is [Item, ...Item[]];

Parameters:

ParameterTypeDescription
valueItem[]the value to check

Returns:

value is [Item, ...Item[]]

function isNull()

Predicate check that value is null

Signature:

export declare function isNull(value: unknown): value is null;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is null

function isNullOrUndefined()

Utility predicate check that value is either null or undefined

Signature:

export declare function isNullOrUndefined(value: unknown): value is null | undefined;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is null | undefined

function isObject()

Predicate check that value is an object.

Signature:

export declare function isObject<Type extends Shape>(value: unknown): value is Type;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is Type

function isPlainObject()

Predicate check for whether passed in value is a plain object

Signature:

export declare function isPlainObject<Type = unknown>(value: unknown): value is UnknownShape<Type>;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is UnknownShape<Type>

function isPrimitive()

Predicate check for whether passed in value is a primitive value

Signature:

export declare function isPrimitive(value: unknown): value is Primitive;

Parameters:

ParameterTypeDescription
valueunknown

Returns:

value is Primitive

function isPromise()

Predicate check that value has the promise api implemented

Signature:

export declare function isPromise(value: unknown): value is Promise<unknown>;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is Promise<unknown>

function isSafeInteger()

Helper function for Number.isSafeInteger allowing for unknown values to be tested

Signature:

export declare function isSafeInteger(value: unknown): value is number;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is number

function isSet()

Predicate check that value is a Set

Signature:

export declare function isSet(value: unknown): value is Set<unknown>;

Parameters:

ParameterTypeDescription
valueunknownthe value to check

Returns:

value is Set<unknown>

function keys()

A typesafe implementation of Object.keys()

Signature:

export declare function keys<Type extends object, Key extends Extract<keyof Type, string>>(value: Type): Key[];

Parameters:

ParameterTypeDescription
valueType

Returns:

Key[]

function last()

Get the last element of the array.

Signature:

export declare function last<Type>(array: Type[]): Type;

Parameters:

ParameterTypeDescription
arrayType[]

Returns:

Type

function noop()

noop is a shorthand way of saying No Operation and is a function that does nothing.

And Sometimes doing nothing is the best policy.

Signature:

export declare function noop(): undefined;

Returns:

undefined

function object()

Creates an object with the null prototype.

Signature:

export declare function object<Type extends object>(value?: Type): Type;

Parameters:

ParameterTypeDescription
valueType(Optional) the object to create

Returns:

Type

function omitUndefined()

Remove the undefined values from an object.

Signature:

export declare function omitUndefined<Type extends object>(object: Type): ConditionalExcept<Type, undefined>;

Parameters:

ParameterTypeDescription
objectType

Returns:

ConditionalExcept<Type, undefined>

function randomFloat()

Generate a random float between min and max. If only one parameter is provided minimum is set to 0.

Signature:

export declare function randomFloat(min: number, max?: number): number;

Parameters:

ParameterTypeDescription
minnumberthe minimum value
maxnumber(Optional) the maximum value

Returns:

number

function randomInt()

Generate a random integer between min and max. If only one parameter is provided minimum is set to 0.

Signature:

export declare function randomInt(min: number, max?: number): number;

Parameters:

ParameterTypeDescription
minnumberthe minimum value
maxnumber(Optional) the maximum value

Returns:

number

function range()

Create a range from start to end.

If only start is provided it creates an array of the size provided. if start and end are provided it creates an array who's first position is start and final position is end. i.e. length = (end - start) + 1.

If you'd like to create a typed tuple of up to 40 items then pass in a [number] tuple as the first argument.

Signature:

export declare function range<Size extends number>(size: [Size]): TupleRange<Size>;

Parameters:

ParameterTypeDescription
size[Size]

Returns:

TupleRange<Size>

function range()

Signature:

export declare function range(size: number): number[];

Parameters:

ParameterTypeDescription
sizenumber

Returns:

number[]

function range()

Signature:

export declare function range(start: number, end: number): number[];

Parameters:

ParameterTypeDescription
startnumber
endnumber

Returns:

number[]

function set()

Set the value of a given path for the provided object. Does not mutate the original object.

Signature:

export declare function set(path: number | string | Array<string | number>, obj: Shape, value: unknown): Shape;

Parameters:

ParameterTypeDescription
pathnumber | string | Array<string | number>
objShape
valueunknown

Returns:

Shape

function shallowClone()

Shallow clone an object while preserving it's getters and setters. This is a an alternative to the spread clone.

Signature:

export declare function shallowClone<Type extends object>(value: Type): Type;

Parameters:

ParameterTypeDescription
valueType

Returns:

Type

function sort()

Sorts an array while retaining the original order when the compare method identifies the items as equal.

Array.prototype.sort() is unstable and so values that are the same will jump around in a non deterministic manner. Here I'm using the index as a fallback. If two elements have the same priority the element with the lower index is placed first hence retaining the original order.

Signature:

export declare function sort<Type>(array: Type[], compareFn: (a: Type, z: Type) => number): Type[];

Parameters:

ParameterTypeDescription
arrayType[]the array to sort
compareFn(a: Type, z: Type) => numbercompare the two value arguments a and z - return 0 for equal - return number > 0 for a > z - return number < 0 for z > a

Returns:

Type[]

function startCase()

Converts a string, including strings in camelCase or snake_case, into Start Case (a variant of Title case where all words start with a capital letter), it keeps original single quote and hyphen in the word.

'management_companies' to 'Management Companies' 'managementCompanies' to 'Management Companies' hell's kitchen to Hell's Kitchen co-op to Co-op

Signature:

export declare function startCase(string: string): string;

Parameters:

ParameterTypeDescription
stringstring

Returns:

string

function take()

Takes a number of elements from the provided array starting from the zero-index

Signature:

export declare function take<Type>(array: Type[], number: number): Type[];

Parameters:

ParameterTypeDescription
arrayType[]
numbernumber

Returns:

Type[]

function toString_2()

Alias of toString for non-dom environments.

This is a safe way of calling toString on objects created with Object.create(null).

Signature:

export declare function toString(value: unknown): string;

Parameters:

ParameterTypeDescription
valueunknown

Returns:

string

function uniqueArray()

Create a unique array in a non-mutating manner

Signature:

export declare function uniqueArray<Type>(array: Type[], fromStart?: boolean): Type[];

Parameters:

ParameterTypeDescription
arrayType[]the array which will be reduced to its unique elements
fromStartboolean(Optional) when set to true the duplicates will be removed from the beginning of the array. This defaults to false.

Returns:

Type[]

a new array containing only unique elements (by reference)

function uniqueBy()

Create a unique array of objects from a getter function or a property list.

Signature:

export declare function uniqueBy<Item = any>(array: Item[], getValue: ((item: Item) => unknown) | string | string[], fromStart?: boolean): Item[];

Parameters:

ParameterTypeDescription
arrayItem[]the array to extract unique values from
getValue((item: Item) => unknown) | string | string[]a getter function or a string with the path to the item that is being used as a a test for uniqueness.
fromStartboolean

(Optional) when true will remove duplicates from the start rather than from the end

import { uniqueBy } from '@remirror/core-helpers';

const values = uniqueBy([{ id: 'a', value: 'Awesome' }, { id: 'a', value: 'ignored' }], item => item.id);
log(values) // => [{id: 'a', value: 'Awesome'}]

const byKey = uniqueBy([{ id: 'a', value: 'Awesome' }, { id: 'a', value: 'ignored' }], 'id')
// Same as above

|

Returns:

Item[]

function uniqueId()

Generate a unique id

Signature:

export declare function uniqueId(prefix?: string): string;

Parameters:

ParameterTypeDescription
prefixstring(Optional) a prefix for the generated id.

Returns:

string

a unique string of specified length

function unset()

Unset the value of a given path within an object.

Signature:

export declare function unset(path: Array<string | number>, target: Shape): Shape;

Parameters:

ParameterTypeDescription
pathArray<string | number>
targetShape

Returns:

Shape

function values()

A typesafe implementation of Object.values()

Signature:

export declare function values<Type extends object, Key extends Extract<keyof Type, string>, Value extends Type[Key]>(value: Type): Value[];

Parameters:

ParameterTypeDescription
valueType

Returns:

Value[]

function within()

Check that a number is within the minimum and maximum bounds of a set of numbers.

Signature:

export declare function within(value: number, ...rest: Array<number | undefined | null>): boolean;

Parameters:

ParameterTypeDescription
valuenumberthe number to test
restArray<number | undefined | null>

Returns:

boolean

variable isArray

Alias the isArray method.

Signature:

isArray: (arg: any) => arg is any[]

variable isDate

Predicate check that value is a date

Signature:

isDate: (value: unknown) => value is Date

variable isEqual

Alias for fast deep equal

Signature:

isEqual: (a: any, b: any) => boolean

variable isError

Predicate check that value is an error

Signature:

isError: (value: unknown) => value is Error

variable isFunction

Predicate check that value is a function

Signature:

isFunction: (value: unknown) => value is AnyFunction

variable isNumber

Predicate check that value is a number.

Also by default doesn't include NaN as a valid number.

Signature:

isNumber: (value: unknown) => value is number

variable isRegExp

Predicate check that value is a RegExp

Signature:

isRegExp: (value: unknown) => value is RegExp

variable isString

Predicate check that value is a string

Signature:

isString: (value: unknown) => value is string

variable isSymbol

Predicate check that value is a symbol

Signature:

isSymbol: (value: unknown) => value is symbol

variable isUndefined

Predicate check that value is undefined

Signature:

isUndefined: (value: unknown) => value is undefined

interface RemirrorErrorOptions

The invariant options which only show up during development.

Signature:

export interface RemirrorErrorOptions 

property code

The code for the built in error.

Signature:

code?: ErrorConstant;

property disableLogging

When true logging to the console is disabled.

Signature:

disableLogging?: boolean;

property message

The message to add to the error.

Signature:

message?: string;

type ClassName

Signature:

export type ClassName<T = string> = T | ClassValue;