File

src/lib/extensions/util.service.ts

Index

Properties
Methods
Accessors

Constructor

constructor()

Methods

Public adjustPrecision
adjustPrecision(value: number, decimals: number, factor: number)

Method to avoid displaying precision issues of javascript floating-point arithmetic. This method was mostly designed for percentage values, when we multiply by 100 a number between 0 and 1, which can trigger the precision issues, but can be used for other cases.

Parameters :
Name Type Optional Default value Description
value number No

The value to adjust its precision.

decimals number No 10

Specifies the maximum number of decimal places to keep when the number is not close to an integer.

factor number No 10

A multiplier for EPSILON to determine the tolerance for detecting floating-point precision issues.

Returns : any
Public applyCeilOrFloor
applyCeilOrFloor(value: Decimal)

Apply ceil if the value is greater than zero, otherwise, apply the floor.

Parameters :
Name Type Optional Description
value Decimal No

The value

Returns : any

The rounded value

Public arrayContainsAll
arrayContainsAll(array: any[], subset: any[], propertiesToEvaluate?: string[])

Check if an array contains all elements from a list

Parameters :
Name Type Optional Description
array any[] No

the array

subset any[] No

elements to check if the array contains all of them

propertiesToEvaluate string[] Yes

properties to consider to decide if array contains element or not

Returns : boolean

true if array contains all

Public arrayMerge
arrayMerge(source1: T[], source2: T[], property: string)
Type parameters :
  • T

This methods merges two object arrays of the same type, using a property as key. Example: let target = [{name: a, title: "title a", subTitle: "subTitle a"}, {name: b, title: "title b", subTitle: "subTitle b"}] let source = [{name: a, title: "new title a"}, {name: c, title: "test c", subTitle: "subTitle c"}] let result = arrayMerge(target, source, "name") Result will be: [{name: a, title: "new title a", subTitle: "subTitle a"}, {name: b, title: "title b", subTitle: "subTitle b"}, {name: c, title: "test c", subTitle: "subTitle c"}]

Parameters :
Name Type Optional Description
source1 T[] No

Source array used for merge

source2 T[] No

Merge property used as key

property string No
Returns : T[]
Public base64stringToByteArray
base64stringToByteArray(base64String: string)

Converts a base64 string to byte array

Parameters :
Name Type Optional Description
base64String string No

base64 string to be converted

Returns : any[]
Public bet
bet(probability: number)

Place a bet and receive a pseudo random result (true or false) (win or loose) with a certain a probability of wining

Parameters :
Name Type Optional Description
probability number No

the probability of wining (0 to 1)

Returns : boolean

boolean (true=win or false=loose)

Public buildUrl
buildUrl(snapshot: ActivatedRouteSnapshot)

Builds an url from an activated route snapshot.

Parameters :
Name Type Optional
snapshot ActivatedRouteSnapshot No
Returns : string
Public buildUrlByConfig
buildUrlByConfig(config: any, resource?: string)
Parameters :
Name Type Optional
config any No
resource string Yes
Returns : string
Public byteArrayToBase64String
byteArrayToBase64String(bytes: Uint8Array)

Converts an array of Bytes into a Base64 string

Parameters :
Name Type Optional Description
bytes Uint8Array No

Bytes to convert

Returns : string

Base64 string

Public calculateColorContrast
calculateColorContrast(backgroundColor: string, foregroundColor: string)
Parameters :
Name Type Optional Description
backgroundColor string No

the background color

foregroundColor string No

the foreground color

Returns : number
Public calculateColorGradient
calculateColorGradient(rgbaColorA: string, rgbaColorB: string, percentage: number, alpha: number)

Calculates the color gradient between two colors Does not keep alpha to calculate gradient

Parameters :
Name Type Optional Default value Description
rgbaColorA string No

rgba(x,x,x) format A color (0 percentage)

rgbaColorB string No

rgba(x,x,x) format B color (100 percentage)

percentage number No

Gradient percentage

alpha number No 1

Optional alpha value. Defaults to 1

Returns : string
Public camelize
camelize(stringToCamelize: string)
Parameters :
Name Type Optional
stringToCamelize string No
Returns : string
Public capitalizeFirstLetter
capitalizeFirstLetter(string)

Capitalize first letter. Note that the search is case insensitive

Parameters :
Name Optional Description
string No

input string

Returns : string

string with the first letter capitalized

Public changeFontIconSize
changeFontIconSize(currentFontClass: string, newSize: IconSize)
Parameters :
Name Type Optional
currentFontClass string No
newSize IconSize No
Returns : string
Public changes
changes(oldArray: T[], newArray: T[], idProperty: string, propertiesToCompare?: string[], compareFunction?: (a?: T,b?: T) => void, considerVoidValues?: boolean, considerEmptyStrings?: boolean)
Type parameters :
  • T

Compares two arrays (old and new) to get the changes between them: New items, Updated items, Removed Items and Untouched Items

to check if the element changed (default behavior will evaluate a 'deep equal', so try to avoid the default behavior and provide properties to compare)

Parameters :
Name Type Optional Default value Description
oldArray T[] No

the old array

newArray T[] No

the new array

idProperty string No 'Id'

[optional] the identification property (default: 'Id')

propertiesToCompare string[] Yes

[optional] an array of properties to compare new element with old element to check if the element changed (default behavior will evaluate a 'deep equal', so try to avoid the default behavior and provide properties to compare)

compareFunction function Yes

the function to compare the values

considerVoidValues boolean Yes

If consider void values -> that is, if "null" or "undefined" can be consider the same (default is strict equals)

considerEmptyStrings boolean Yes

If true: null, undefined and "" are considered the same

Returns : literal type

the changes in format {added: any[], updated: any[], removed: any[], untouched: any[]}

Public checkMat
checkMat(mat: number[][], start: literal type, range: literal type, valueToCheck: number)

Check if a given value exists in the supplied matrix

Parameters :
Name Type Optional Default value Description
mat number[][] No

Matrix to test

start literal type No

Matrix start checking position position

range literal type No

Matrix range

valueToCheck number No 0

Value to check if exists in the matrix

Returns : boolean

True if value found in the range of the supplied matrix

Public checkNestedPropertyByArray
checkNestedPropertyByArray(sourceObject: Object, propertyArray: string[])

This method check if the properties given exist on the object For example, considering the next object literal: sourceObject: { prop1: { prop2 : { prop3: 123 } } } Passing the following path ["prop1", "prop2", "prop3"] will return true if all properties exist

Parameters :
Name Type Optional Description
sourceObject Object No

The source object to start property navigation

propertyArray string[] No
Returns : boolean

returns true if properties exist and false otherwise

Public checkNestedPropertyByPath
checkNestedPropertyByPath(sourceObject: T, path: PropertyPath<T>)
Type parameters :
  • T

This method check if the properties given exist on the object For example, considering the next object literal: sourceObject: { prop1: { prop2 : { prop3: 123 } } } Passing the following path "prop1.prop2.prop3" will return true if all properties exist

Parameters :
Name Type Optional Description
sourceObject T No

The source object to start property navigation

path PropertyPath<T> No

String path

Returns : boolean

returns true if properties exist and false otherwise

Public colorHEXtoRGBA
colorHEXtoRGBA(hexColor: string, alfa?: number)

Converts a color string representation (components) from HEX format to RGB[A] format

Parameters :
Name Type Optional Description
hexColor string No

String with a color representation in the format 'rgb(r,g,b)' or 'rgba(r,g,b,a)'

alfa number Yes

the alfa to apply to the color [optional]

Returns : string

color string representation in the format "#XXXXXX"

Public colorHSLtoRGB
colorHSLtoRGB(color: string)

Converts a color string representation (components) from HSL format to RGB[A] format

Parameters :
Name Type Optional Description
color string No

String with a color representation in the format 'hsl(h,s,l)'

Returns : { r: any; g: any; b: any; }

color values in the format "{r: number, g: number, b: number}"

Public colorRGBAtoHEX
colorRGBAtoHEX(rgbaColor: string)

Converts a color string representation (components) from RGB[A] format to HEX format

Parameters :
Name Type Optional Description
rgbaColor string No

string representation in the format 'rgb(r,g,b)' or 'rgba(r,g,b,a)'

Returns : string

color string representation in the format "#XXXXXX"

Public colorRGBtoHSL
colorRGBtoHSL(color: string)

Converts a color string representation (components) from RGB[A] format to HSL format

Parameters :
Name Type Optional Description
color string No

String with a color representation in the format 'rgb(r,g,b)' or 'rgba(r,g,b,a)'

Returns : literal type

color values in the format "{hue: number, saturation: number, lightness: number}"

Public compare
compare(firstValue: any, secondValue: any, fieldOperator: Cmf.Foundation.Common.FieldOperator)

Compares two values using a given field operator. This methods assumes that the given values can be properly compared using the given fieldOperator

Parameters :
Name Type Optional Description
firstValue any No

first value in the comparison

secondValue any No

second value in the comparison

fieldOperator Cmf.Foundation.Common.FieldOperator No
Returns : boolean

true if the comparison is true

Public compareColors
compareColors(colorA: string, colorB: string, similarityOffset: number)

Checks if two colors are equal 0 means that colors must be completely equal, 1 means that colors are completely different

Parameters :
Name Type Optional Default value Description
colorA string No

color A

colorB string No

color B

similarityOffset number No 0
Returns : boolean

if the two colors are similar or not

Public compareComplexTypes
compareComplexTypes(first: ComplexType, second: ComplexType)

Compares the two provided complex types

Parameters :
Name Type Optional Description
first ComplexType No

First complex type to compare

second ComplexType No

Second complex type to compare

Returns : boolean
Public convertCssColorToRGB
convertCssColorToRGB(color: string)

Converts css valid color to a RGB string Validated cases:

  • hex (ex: #FFF000)
  • rgb (ex: rgb(255, 0, 0))
  • name (ex: red, white...)
  • hsl (ex: hsl(0, 100%, 50%))
Parameters :
Name Type Optional Description
color string No

Color to convert

Returns : string

color string

Public convertCssColorToRGBComponents
convertCssColorToRGBComponents(color: string, normalize?: boolean)

Converts css valid color to RGB components separated in numbers Validated cases:

  • hex (ex: #FFF000)
  • rgb (ex: rgb(255, 0, 0))
  • name (ex: red, white...)
  • hsl (ex: hsl(0, 100%, 50%))
Parameters :
Name Type Optional Description
color string No

Color to convert

normalize boolean Yes
Returns : literal type

color components

Public convertFileSize
convertFileSize(value: any, from: FileSizeUnit, to: FileSizeUnit)

Convert from source file size unit to target file size unit

Parameters :
Name Type Optional Description
value any No

the value to convert

from FileSizeUnit No

the file size unit from the value

to FileSizeUnit No

the file size unit to be converted

Returns : number
Public convertMapToObject
convertMapToObject(map: Map)
Type parameters :
  • T

Convert Map to object

Parameters :
Name Type Optional
map Map<string | T> No
Returns : Record<string, T>

Object after conversion

Public convertObjectToMap
convertObjectToMap(object: Record)
Type parameters :
  • T

Convert Object to Map

Parameters :
Name Type Optional
object Record<string | T> No
Returns : Map<string, T>

Map after conversion

Public convertToReadableFileSize
convertToReadableFileSize(value: any, from: FileSizeUnit, to: FileSizeUnit)

Convert from value to readable file size unit

Parameters :
Name Type Optional Description
value any No

the value to convert

from FileSizeUnit No

the file size unit from the value

to FileSizeUnit No

the file size unit to be converted

Returns : string
Public createObject
createObject(constructor, properties: Partial<>)
Type parameters :
  • T

Creates an object using the constructor and assigns the provided properties.

Parameters :
Name Type Optional Description
constructor No

The object constructor to create.

properties Partial<> No

The object properties to assign.

Returns : T
Public createWebWorker
createWebWorker(data: string, isCode?: boolean)

Create a new web worker

Parameters :
Name Type Optional Description
data string No

javascript file url or inline javascript code for webworker

isCode boolean Yes

if data is javascript file URL or javascript code

Returns : any
Public curry
curry(func: Function, ...args: any[])
Parameters :
Name Type Optional
func Function No
args any[] No
Returns : Function
Public decamelize
decamelize(camelCase: string, delimiter: string)
Parameters :
Name Type Optional
camelCase string No
delimiter string No
Returns : string
Public deduceReferenceTypeFromInstance
deduceReferenceTypeFromInstance(instance: Cmf.Foundation.Common.Base.CoreBase)

Deduce reference type from instance

Parameters :
Name Type Optional Description
instance Cmf.Foundation.Common.Base.CoreBase No

Instance to deduce reference type from

Returns : ReferenceType

instance's ReferenceType

Public deepAssign
deepAssign(target: T, ...sources: T[])
Type parameters :
  • T

This methods merges any given sources into the target object

Parameters :
Name Type Optional
target T No
sources T[] No
Returns : T
Public deepClone
deepClone(value: T, levelsToClone?: number, cloneSameObjectsOnce?: boolean)
Type parameters :
  • T

Deep clone an object/array/map.

In a Map both keys and values are cloned. Functions are not cloned. and the respective reference is reused (default = true)

Parameters :
Name Type Optional Description
value T No

Value to be cloned

levelsToClone number Yes

Number of levels to recursively clone (default = 10)

cloneSameObjectsOnce boolean Yes

If true, any object that is referenced more than once is cloned only once and the respective reference is reused (default = true)

Returns : T
Public deleteAllCookies
deleteAllCookies()

Delete all cookies

Returns : void
Public deleteCookieByName
deleteCookieByName(name: string)

Delete a cookie

Parameters :
Name Type Optional Description
name string No

, cookie name

Returns : void
Public deleteNestedPropertyByArray
deleteNestedPropertyByArray(sourceObject: Object, propertyArray: string[])

This method deletes a property from an object based on the supplied path. For example, considering the next object literal: sourceObject: { prop1: { prop2 : { prop3: 123 prop4: 456 } } } Passing an array literal like ["prop1", "prop2", "prop3"] will delete property "prop3". The resulting source object would be: sourceObject: { prop1: { prop2 : { prop4: 456 } } }

Parameters :
Name Type Optional Description
sourceObject Object No

The source object to delete the property from

propertyArray string[] No

An array of properties that define the path of the property to delete

Returns : boolean

returns false if a given property was not found and true if the field was deleted sucessfully

Public deleteNestedPropertyByPath
deleteNestedPropertyByPath(sourceObject: T, path: PropertyPath<T>)
Type parameters :
  • T

This method deletes a property from an object based on the supplied path. For example, considering the next object literal: sourceObject: { prop1: { prop2 : { prop3: 123 prop4: 456 } } } Passing the path "prop1.prop2.prop3" will delete property "prop3". The resulting source object would be: sourceObject: { prop1: { prop2 : { prop4: 456 } } }

Parameters :
Name Type Optional Description
sourceObject T No

The source object to delete the property from

path PropertyPath<T> No

The path of the property to delete

Returns : boolean

returns false if a given property was not found and true if the field was deleted successfully

Public durationToString
durationToString(duration: moment.Duration, format: string)

Transforms a moment duration into a string in the format sent as an input

Parameters :
Name Type Optional Description
duration moment.Duration No

the duration to put as a string

format string No

string format

Returns : string
Public endsWith
endsWith(original: string, suffix: string)
Parameters :
Name Type Optional
original string No
suffix string No
Returns : boolean
Public escapeHtml
escapeHtml(unsafe: string)

Escapes HTML special characters in a string

Parameters :
Name Type Optional Description
unsafe string No

string to be escaped

Returns : string

string escaped

Public escapeRegExp
escapeRegExp(string: string)

Escapes a string to be used in a RegExp

Parameters :
Name Type Optional Description
string string No

string to be escaped

Returns : string
Public fade
fade(color: string, percentage?: number)

Applies a transparency to a color in the formats RGB[A] or HEX

Parameters :
Name Type Optional Description
color string No

String with a color representation in the format 'rgb(r,g,b)' or 'rgba(r,g,b,a)' or '#XXXXXX'

percentage number Yes

the percentage of transparency to apply to the color

Returns : string

color string representation in the format 'rgba(r,g,b,a)'

Public fillMat
fillMat(mat: number[][], start: literal type, range: literal type, valueToAdd: number)

Fills (or creates) a matrix within the supplied range

Parameters :
Name Type Optional Default value Description
mat number[][] No

Matrix to test

start literal type No

Matrix start checking position position

range literal type No

Matrix range

valueToAdd number No 0

Value to add in all the positions present in the supplied range

Returns : [][]

Created/Update matrix

Public generateColorsArray
generateColorsArray(numberOfColors: number, useDefault: boolean)

Generates an array of colors

Parameters :
Name Type Optional Description
numberOfColors number No

number of colors to generate

useDefault boolean No

if is to use default colors (only if numberOfColors <= 20)

Returns : string[]
Public generateColorsToArrayOfItems
generateColorsToArrayOfItems(items: any[], colorField: string, useDefault: boolean)

Generates a different color for each item of an array and puts the value in a "color field"

Parameters :
Name Type Optional Description
items any[] No

array of items

colorField string No

the item color field

useDefault boolean No

if is to use default colors (only if items count <= 20)

Returns : any[]
Public generateHashCode
generateHashCode(text: string)

Generate HashCode from string

Parameters :
Name Type Optional Description
text string No

String to hash

Returns : string
Public getCookieByName
getCookieByName(name: string)

Gets the value of the cookie with the given name.

Parameters :
Name Type Optional Description
name string No

Name of the cookie

Returns : string

The value of the cookie, or null if named cookie doesn't exist.

Public getCssVariable
getCssVariable(variable: string)

Retrieves a value from a CSS variable from the DOM

Parameters :
Name Type Optional Description
variable string No

String with teh css variable name

Returns : string

variable value

Public getElementByFieldPath
getElementByFieldPath(fieldPath: string, fieldValue: any, collection: any[])

Gets an element with a specific field from the provided collection

Parameters :
Name Type Optional Description
fieldPath string No
fieldValue any No

field value used in the comparison

collection any[] No

array of objects. Each element must have a key named id

Returns : any
Public getElementById
getElementById(id: string, collection: any[])

Gets an element with a specific id from the provided collection

Parameters :
Name Type Optional Description
id string No

element id

collection any[] No

array of objects. Each element must have a key named id

Returns : any
Public getEnumValue
getEnumValue(value: string | number, enumObj: object | string)

Based on a value (string | number) searches for that value in the supplied enum object (or string with the Enum's FullName), and always returns a number.

Parameters :
Name Type Optional Description
value string | number No

enum value to search for, can be either string or number

enumObj object | string No

Enum object which contains all the enum values or a string with the Enum's FullName

Returns : number
Public getFileMimeType
getFileMimeType(fileName: string, contentTypeTableArray: Object[])

Given a file name (with extension), and the list of available mime types will return the correct mime type

Parameters :
Name Type Optional Description
fileName string No

File name with extension

contentTypeTableArray Object[] No

Available content types

Returns : string
Public getHTMLText
getHTMLText(html: string)

Get HTML text from string

Parameters :
Name Type Optional Description
html string No

the html string

Returns : string

the html text content

Public getIndexByFieldPath
getIndexByFieldPath(fieldPath: string, fieldValue: any, collection: any[])

Gets an element with a specific field from the provided collection

Parameters :
Name Type Optional Description
fieldPath string No
fieldValue any No

field value used in the comparison

collection any[] No

array of objects. Each element must have a key named id

Returns : number
Public getIndexById
getIndexById(id: string, collection: any[])

Gets an element index with a specific id from the provided collection

Parameters :
Name Type Optional Description
id string No

element id

collection any[] No

array of objects. Each element must have a key named id

Returns : number
Public getInputSelection
getInputSelection(input: HTMLInputElement)

Gets the current selection range of the provided html input

Parameters :
Name Type Optional
input HTMLInputElement No
Public getInstancesFromContext
getInstancesFromContext(context: any)

Get the available instances from the context

Parameters :
Name Type Optional Description
context any No

The context from which the instances will be retrieved

Returns : Cmf.Foundation.Common.Base.CoreBase[]
Public getNumericValue
getNumericValue(value: any)

Gets the numeric value of the passed value (could be string, number or decimal.js object)

Parameters :
Name Type Optional
value any No
Returns : any
Public getNumericValueStr
getNumericValueStr(value: any)

Gets the numeric value of the passed value (could be string, number or decimal.js object)

Parameters :
Name Type Optional
value any No
Returns : string
Public getObjectByNamespace
getObjectByNamespace(startObject: Object, namespaceArray: string[])
Parameters :
Name Type Optional
startObject Object No
namespaceArray string[] No
Returns : any
Public getObjectProperties
getObjectProperties(object: any, levelsToLoad: number, currentLvl: number)

Get Object Properties with levels to load of an object instance. Useful to send in service inputs where only this information is needed, avoiding extra payload on service request.

Parameters :
Name Type Optional Default value Description
object any No

object

levelsToLoad number No

levels to load

currentLvl number No 1

default: 1; this variable is only used internally (recursive scenario)

Returns : any
Public getObjectThatImplementsFunction
getObjectThatImplementsFunction(object: any, functionToLook: string)
Parameters :
Name Type Optional
object any No
functionToLook string No
Returns : any
Public getReadableFileSizeUnit
getReadableFileSizeUnit(value: any)

Returns the highest order of magnitude for the size value

Parameters :
Name Type Optional Description
value any No

the size value

Returns : FileSizeUnit

the highest order of magnitude for the size value

Public getScript
getScript(script: string)
Parameters :
Name Type Optional
script string No
Returns : Promise<any>
Public getScripts
getScripts(...scripts: (string | string[])[])
Parameters :
Name Type Optional
scripts (string | string[])[] No
Returns : Promise<any[]>
Public getThemeColor
getThemeColor(colorCSSVariable: string, fade?: number)

Retrieves color from the theme EX: getThemeColor("color-red",60) which means the "color-red" with 60% opacity or getThemeColor("styleColor004") which means the color "styleColor004" with 100% opacity or getThemeColor("--styleColor001",25) which means the color "styleColor001" with 25% opacity

Parameters :
Name Type Optional Description
colorCSSVariable string No

the color css variable name (can omit the '--' in the beginning of the color variable name')

fade number Yes

fade to apply to the color [optional]

Returns : string

variable value in RGBA format (Ex: 'rgba(255,255,255,0.5)')

Public getTypeString
getTypeString(type: SimpleType | ComplexType)

Gets a string representation of a SimpleType or a ComplexType

Parameters :
Name Type Optional Description
type SimpleType | ComplexType No

Supplied simple or complex type

Returns : string
Public getValidOperatorsForType
getValidOperatorsForType(type: ComplexType)

Get all valid field operators for a given type

Parameters :
Name Type Optional Description
type ComplexType No

supplied complex type

Returns : Cmf.Foundation.Common.FieldOperator[]

collection of field operators

Public getWeekDays
getWeekDays()

Returns all the week days. The day number is 1-based index, which means that 'Sunday' is day 1 and so on.

Returns : WeekDay[]
Public hasInvalidEmails
hasInvalidEmails(emails: string[], invalidEmails: string[])

Checks if a given value is of type valid for email regex pattern

Parameters :
Name Type Optional Default value Description
emails string[] No

List of email values to check for validity

invalidEmails string[] No []

Output array to collect invalid email strings

Returns : boolean

True if there is any invalid email in the list, false otherwise

Public humanizeDuration
humanizeDuration(duration: moment.Duration, shortFormat?: boolean, precision?: TimeUnit, separator: string)

Humanize a duration printing it to a string in the format: (EX: 2 hours 1 minute)

Parameters :
Name Type Optional Default value Description
duration moment.Duration No

the duration to humanize

shortFormat boolean Yes

short humanize format (ex: 2h 1m)

precision TimeUnit Yes

duration precision (ex: 2h 1m 2ms has a millisecond precision)

separator string No ' '

units separator (ex: 2h:1m). Defaults to space (ex: 2h 1m)

Returns : string
Public humanizeDurationInSeconds
humanizeDurationInSeconds(durationInSeconds: number, timeunit: TimeUnit)

Humanize duration in seconds

Parameters :
Name Type Optional Default value
durationInSeconds number No
timeunit TimeUnit No TimeUnit.Second
Returns : string

the humanized duration

Public includesIgnoreCase
includesIgnoreCase(a: string, b: string)

Check if a string is null or does not contain text

Parameters :
Name Type Optional
a string No
b string No
Returns : boolean
Public inferPropertyType
inferPropertyType(value: any)

Infer Simple Type from value

Parameters :
Name Type Optional
value any No
Returns : PropertyType
Public inferStringValueAccordingToPropertyType
inferStringValueAccordingToPropertyType(value: any)

Infer string value according to Property Type

Parameters :
Name Type Optional
value any No
Returns : string
Public instanceof
instanceof(objectToTest: Object, constructor, objectToTestConstructor?: Function, rootObject?: Object)
Type parameters :
  • T

Checks if a passed object is an instance of the passed constructor function pass in the Material constructor right away to test if a Material object is an EntityInstance. the method will extract a constructor to use. For instance, to test Material against EntityInstance, one can pass in the root "Cmf" object so all properties are navigated until the Material constructor is found. The method will have a commodity of checking the Material constructor name and still be able to use the "Cmf" root object without even passing this parameter.

Parameters :
Name Type Optional Description
objectToTest Object No

Object to test the instance

constructor No

Constructor to test against

objectToTestConstructor Function Yes

In case of prototype chain check, one can pass in the constructor of the objectToTest, for instance, pass in the Material constructor right away to test if a Material object is an EntityInstance.

rootObject Object Yes

In case of prototype chain check, one can pass in the root object from which the method will extract a constructor to use. For instance, to test Material against EntityInstance, one can pass in the root "Cmf" object so all properties are navigated until the Material constructor is found. The method will have a commodity of checking the Material constructor name and still be able to use the "Cmf" root object without even passing this parameter.

Returns : T

True in case the object is really an instance of, false otherwise.

Public isDuration
isDuration(value: moment.Duration)

Checks if supplied duration is duration Used in scenarios where the object was cloned and the moment.IsDuration no longer works

Parameters :
Name Type Optional Description
value moment.Duration No

Value to check if is duration

Returns : boolean

True if is duration (has function asMilliseconds, false otherwise)

Public isEqual
isEqual(object: any, other: any, propertiesToCompare?: string[], considerVoidValues?: boolean, considerEmptyStrings?: boolean)

Performs a deep comparison between the two objects, to determine if they should be considered equal. For Maps its compare its keys and values using underscore isEqual For other type of object it compares automatically using underscore isEqual method

Parameters :
Name Type Optional Description
object any No

Compare to other.

other any No

Compare to object.

propertiesToCompare string[] Yes

Default properties to compare

considerVoidValues boolean Yes

If consider void values -> that is, if "null" or "undefined" can be consider the same (default is strict equals)

considerEmptyStrings boolean Yes

If true: null, undefined and "" are considered the same

Returns : boolean

True if object is equal to other.

Public isHexColor
isHexColor(hex: string)

Determines whether is hex color

Parameters :
Name Type Optional Description
hex string No

hex value to check

Returns : boolean

true if hex color

Public isInteger
isInteger(value)

Checks if a passed value is integer

Parameters :
Name Optional
value No
Returns : string | number | Decimal
Public isJsonString
isJsonString(str: string)

Check if the given string contains valid JSON.

Parameters :
Name Type Optional Description
str string No

JSON String

Returns : boolean
Public isNullOrEmpty
isNullOrEmpty(value: string)

Check if a string is null or does not contain text

Parameters :
Name Type Optional Description
value string No

string to check

Returns : boolean

true, if the provided string is nullish or if it's empty

Public isNullOrWhiteSpace
isNullOrWhiteSpace(value)

Check if a string is null or contains only whitespace

Parameters :
Name Optional Description
value No

string to check

Returns : boolean

true, if the provided string is nullish or if it's only whitespace

Public isNumeric
isNumeric(value)

Checks if a passed value is numeric

Parameters :
Name Optional
value No
Returns : string | number | Decimal
Public isPromise
isPromise(value)

Checks if a given value is o type Promise

Parameters :
Name Optional
value No
Returns : any
Public isValidCssColor
isValidCssColor(color: string)

Determines whether is a valid css color Validated cases:

  • hex (ex: #FFF000)
  • rgb (ex: rgb(255, 0, 0))
  • name (ex: red, white...)
  • hsl (ex: hsl(0, 100%, 50%))
Parameters :
Name Type Optional Description
color string No

Color to test

Returns : boolean
Public isValidEmail
isValidEmail(email: string)

Checks if a given value is o type valid for email regex pattern

Parameters :
Name Type Optional Description
email string No

Value to check if is a valid email

Returns : boolean

True if email value matches the email pattern

Public mapUnique
mapUnique(array: any[], iterator: (item: any,index: number) => void)

Performs the same as the Array.map function but the result comes without repeated values

Parameters :
Name Type Optional Description
array any[] No

the array

iterator function No

the iterator function to retrieve the value from each item

Returns : any[]

mapped array with unique values

Public momentToTicks
momentToTicks(momentDate: moment.Moment)

Creates the number of ticks from a moment date object.

Parameters :
Name Type Optional Description
momentDate moment.Moment No

moment date object.

Returns : number
Public nameOf
nameOf(name: Extract)
Type parameters :
  • T

Get the property name of T if exists (error otherwise) Note: use this to force strongly-typed checks when using interfaces

Parameters :
Name Type Optional Description
name Extract<T | string> No

Property name

Returns : string

The same property name Note: use this to force strongly-typed checks when using interfaces

Public navigateNestedPropertyByArray
navigateNestedPropertyByArray(sourceObject: Object, propertyArray: string[])

This method navigates an object based on a set of properties. For example, considering the next object literal: sourceObject: { prop1: { prop2 : { prop3: 123 } } } Passing an array literal like ["prop1", "prop2", "prop3"] will return 123. The method navigates all nested objects based on an array of properties

Parameters :
Name Type Optional Description
sourceObject Object No

The source object to start property navigation

propertyArray string[] No

An array with all nested properties to search for

Returns : any

returns null if a given property was not found or the value of all met properties

Public navigateNestedPropertyByPath
navigateNestedPropertyByPath(sourceObject: T, path: PropertyPath<T>)
Type parameters :
  • T

This method navigates an object based on a set of properties. For example, considering the next object literal: sourceObject: { prop1: { prop2 : { prop3: 123 } } } Passing the following path "prop1.prop2.prop3" will return 123. The method navigates all nested objects based on the provided path

Parameters :
Name Type Optional Description
sourceObject T No

The source object to start property navigation

path PropertyPath<T> No

String path

Returns : any

returns null if a given property was not found or the value of all met properties

Public navigateNestedPropertyByString
navigateNestedPropertyByString(sourceObject: Object, property: string)

This method navigates an object based on a single property. For example, considering the next object literal: sourceObject: { prop1: { prop1 : { prop1: 123 } } } Passing the string literal "prop1" will return 123. The method navigates all nested objects for the same property until the last level the property is available.

Parameters :
Name Type Optional Description
sourceObject Object No

The source object to start property navigation

property string No

The property to search for

Returns : any

returns the last value where the property was found, null, if none was found

Public openOrDownloadFile
openOrDownloadFile(file: Blob | string, fileName: string, isToOpen: boolean)

Open or download a File

Parameters :
Name Type Optional Description
file Blob | string No

File to open or download or url to file (image data url, link, etc...)

fileName string No

File name

isToOpen boolean No

If true will be open if false will be downloaded

Returns : void
Public parseType
parseType(type: SimpleType | ComplexType)

Parses a type (simple or complex), the result is always a ComplexType. Used mainly for type comparison

Parameters :
Name Type Optional Description
type SimpleType | ComplexType No

simple or complex type to be parsed

Returns : ComplexType

Complex type

Public partialClone
partialClone(obj: T, propertiesToClone: string[])
Type parameters :
  • T

Return a copy of the object containing only the specified properties

Parameters :
Name Type Optional Description
obj T No

Original object to clone

propertiesToClone string[] No

List of properties to clone

Returns : T
Public pascalize
pascalize(stringToPascalize: string)
Parameters :
Name Type Optional
stringToPascalize string No
Returns : string
Public prettifyVersionedObject
prettifyVersionedObject(object: Cmf.Foundation.BusinessObjects.EntityVersion, isToShowVersion: boolean)

It prettifies an versioned object with the following format <name> [<revision>.<version>]

Parameters :
Name Type Optional Description
object Cmf.Foundation.BusinessObjects.EntityVersion No

The object to prettify

isToShowVersion boolean No

True if it is to show the Version, false otherwise

Returns : string
Public printDocument
printDocument(documentContent: string)

Prints and html element content using browser printing.

Parameters :
Name Type Optional Description
documentContent string No

HTML element content to print.

Returns : void
Public removeFromCollection
removeFromCollection(itemsToRemove: any[], collection: any[], itemsToRemovePath?: string, collectionPath?: string)

Remove supplied items from the supplied collection

Parameters :
Name Type Optional Description
itemsToRemove any[] No

items to remove form collection

collection any[] No

Collection to remove items from

itemsToRemovePath string Yes

Field to search in the items to remove

collectionPath string Yes

Field to search in the items of the collection

Returns : any[]

The update array

Public removeMultipleSpaces
removeMultipleSpaces(text: string, allowDoubleSpacesInNames)

Removes multiple spaces from a string and trims it

Parameters :
Name Type Optional Default value Description
text string No

string

allowDoubleSpacesInNames No false

boolean that defines if double spaces are allowed

Returns : string
Public round
round(n: number, roundingError?: number, dp: number)

Round to a maximum amount of decimal places

Parameters :
Name Type Optional Default value Description
n number No

number to be rounded

roundingError number Yes

additional rounding error to add to initial number

dp number No 8

maximum amount of decimal places

Returns : number
Public sanitize
sanitize(source: string)

Sanitize string with DOMPurify

Parameters :
Name Type Optional Description
source string No

String to be sanitized

Returns : string

A string that can be written into a DOM element using innerHTML

Public separateNameByUpperCase
separateNameByUpperCase(name: string)

Separates any given name by the upper case characters

Parameters :
Name Type Optional Description
name string No

Name to be separated

Returns : string
Public setInputCaretPos
setInputCaretPos(input: HTMLInputElement, pos: number)

Sets the caret position of a html input

Parameters :
Name Type Optional
input HTMLInputElement No
pos number No
Returns : void
Public setInputSelection
setInputSelection(input: HTMLInputElement, selectionStart: number, selectionEnd: number)

Sets the selection range of a html input

Parameters :
Name Type Optional
input HTMLInputElement No
selectionStart number No
selectionEnd number No
Returns : void
Public setNestedPropertyByArray
setNestedPropertyByArray(sourceObject: Object, propertyArray: string[], value: any, createFields: boolean)

This method updates a property of an object, based on the set of properties and a new value. sourceObject: { prop1: { prop2 : { prop3: 123 } } } Passing an array literal like ["prop1", "prop2", "prop3"] and a value like "456", will change prop3 from "123" to "456". It creates nested objects along the way

Parameters :
Name Type Optional Description
sourceObject Object No

The source object to start property navigation

propertyArray string[] No

An array with all nested properties to search for

value any No

New value for property

createFields boolean No

Defines if the method can created nested objects if needed

Returns : boolean

returns false if a given property was not found and true if the field was updated successfully

Public setNestedPropertyByPath
setNestedPropertyByPath(sourceObject: T, path: PropertyPath<T>, value: any, createFields: boolean)
Type parameters :
  • T

This method updates a property of an object, based on the set of properties and a new value. sourceObject: { prop1: { prop2 : { prop3: 123 } } } Passing an array literal like ["prop1", "prop2", "prop3"] and a value like "456", will change prop3 from "123" to "456". The method navigates all nested objects based on an array of properties

Parameters :
Name Type Optional Description
sourceObject T No

The source object to start property navigation

path PropertyPath<T> No

String path

value any No

New value for property

createFields boolean No

Defines if the method can created nested objects if needed

Returns : boolean

returns false if a given property was not found and true if the field was updated successfully

Public simulateDragAndDropEvent
simulateDragAndDropEvent(sourceSelector: string, targetSelector: string, sourceIndex: number, targetIndex: number)

Simulate drag & drop event

Parameters :
Name Type Optional Default value Description
sourceSelector string No

the source element selector

targetSelector string No

the target element selector

sourceIndex number No 0
targetIndex number No 0
Returns : void
Public Async sleep
sleep(ms: number)

Custom sleep async method

Parameters :
Name Type Optional Description
ms number No

Time to sleep in milliseconds

Returns : Promise<void>
Public sort
sort(collection: T[], path?: string, fieldSort?: Cmf.Foundation.Common.FieldSort)
Type parameters :
  • T

Sorts an array of objects by a given property path (alphabetically ascending/descending)

Example: collection = [{"x":{"y":"d"},"z":"a"},{"x":{"y":"c"},"z":"b"}]; sort(collection, "x.y", Cmf.Foundation.Common.FieldSort.Ascending) = [{"x":{"y":"c"},"z":"b"},{"x":{"y":"d"},"z":"a"}] sort(collection, "z", Cmf.Foundation.Common.FieldSort.Descending) = [{"x":{"y":"c"},"z":"b"},{"x":{"y":"d"},"z":"a"}]

Parameters :
Name Type Optional Description
collection T[] No

collection of objects/strings

path string Yes

property path, same for all provided objects

fieldSort Cmf.Foundation.Common.FieldSort Yes

defines the sort order Example: collection = [{"x":{"y":"d"},"z":"a"},{"x":{"y":"c"},"z":"b"}]; sort(collection, "x.y", Cmf.Foundation.Common.FieldSort.Ascending) = [{"x":{"y":"c"},"z":"b"},{"x":{"y":"d"},"z":"a"}] sort(collection, "z", Cmf.Foundation.Common.FieldSort.Descending) = [{"x":{"y":"c"},"z":"b"},{"x":{"y":"d"},"z":"a"}]

Returns : T[]
Public strLike
strLike(source: string, search: string)

Searches the source string for the given search string, the behavior is similar to the well know SQL like operator. Note that the search is case insensitive

Parameters :
Name Type Optional
source string No
search string No
Returns : boolean
Public supportsMimeType
supportsMimeType(mimeType: string)

Check if browser supports mime type so that we can open file directly on browser

Parameters :
Name Type Optional Description
mimeType string No

mime type

Returns : boolean
Public ticksToDuration
ticksToDuration(ticks: number)

Create a moment duration from ticks.

Parameters :
Name Type Optional Description
ticks number No

number of ticks.

Returns : moment.Duration
Public ticksToMoment
ticksToMoment(ticks: number)

Create a moment date in UTC from ticks.

Parameters :
Name Type Optional Description
ticks number No

number of ticks.

Returns : moment.Moment
Public toBoolean
toBoolean(value)

Converts the provided value to a boolean. If the provided value is a string, the following values are converted to true (case insensitive):

  • 'true'
  • 'yes'
  • 'y'
  • '1'
Parameters :
Name Optional Description
value No

The value being converted

Returns : boolean

The boolean representation of the value

Public toDecimal
toDecimal(value: string)
Parameters :
Name Type Optional
value string No
Returns : Decimal
Public toLong
toLong(value: string)
Parameters :
Name Type Optional
value string No
Returns : Decimal
Public uniqueId
uniqueId(prefix?: string)

Get unique id based on the current date

Parameters :
Name Type Optional
prefix string Yes
Returns : string
Public uuidv4
uuidv4()

Generate UUID

Returns : any
Public waitFor
waitFor(stopCondition: () => void, timeout?: number)

WaitFor Try to execute an action periodically until the stop condition is met or the number of tries reach 0

Parameters :
Name Type Optional Description
stopCondition function No

the condition to execute the action

timeout number Yes

max time the 'waitFor' will run [optional]

Returns : Promise<boolean>

Properties

Public _
Type : _.UnderscoreStatic
Default value : _
Public distributionListMailValidator
Type : ValueValidator
Default value : ((distributionList: string) => { return Promise.resolve(this.isValidEmail(distributionList)); })

Validate that a string representing a distribution list is well formed.

Parameters :
Name Description
distributionList

Distribution List

Public each
Default value : $.each
Public extend
Default value : $.extend
Public integerValidator
Type : ValueValidator
Default value : ((number: string) => { return Promise.resolve(this.isInteger(number)); })

Validate that a string representing a integer is well formed.

Parameters :
Name Description
number

Number to validate

Public numericValidator
Type : ValueValidator
Default value : ((number: string) => { return Promise.resolve(this.isNumeric(number)); })

Validate that a string representing a number is well formed.

Parameters :
Name Description
number

Number to validate

Public uniq
Default value : _.uniq

Accessors

iconRegex
geticonRegex()

results matching ""

    No results matching ""